add GENDER support to revision-info
[lhc/web/wiklou.git] / includes / Article.php
1 <?php
2 /**
3 * File for articles
4 * @file
5 */
6
7 /**
8 * Class representing a MediaWiki article and history.
9 *
10 * See design.txt for an overview.
11 * Note: edit user interface and cache support functions have been
12 * moved to separate EditPage and HTMLFileCache classes.
13 *
14 */
15 class Article {
16 /**@{{
17 * @private
18 */
19 var $mComment = ''; //!<
20 var $mContent; //!<
21 var $mContentLoaded = false; //!<
22 var $mCounter = -1; //!< Not loaded
23 var $mCurID = -1; //!< Not loaded
24 var $mDataLoaded = false; //!<
25 var $mForUpdate = false; //!<
26 var $mGoodAdjustment = 0; //!<
27 var $mIsRedirect = false; //!<
28 var $mLatest = false; //!<
29 var $mMinorEdit; //!<
30 var $mOldId; //!<
31 var $mPreparedEdit = false; //!< Title object if set
32 var $mRedirectedFrom = null; //!< Title object if set
33 var $mRedirectTarget = null; //!< Title object if set
34 var $mRedirectUrl = false; //!<
35 var $mRevIdFetched = 0; //!<
36 var $mRevision; //!<
37 var $mTimestamp = ''; //!<
38 var $mTitle; //!<
39 var $mTotalAdjustment = 0; //!<
40 var $mTouched = '19700101000000'; //!<
41 var $mUser = -1; //!< Not loaded
42 var $mUserText = ''; //!<
43 var $mParserOptions; //!<
44 /**@}}*/
45
46 /**
47 * Constructor and clear the article
48 * @param $title Reference to a Title object.
49 * @param $oldId Integer revision ID, null to fetch from request, zero for current
50 */
51 public function __construct( Title $title, $oldId = null ) {
52 $this->mTitle =& $title;
53 $this->mOldId = $oldId;
54 }
55
56 /**
57 * Constructor from an article article
58 * @param $id The article ID to load
59 */
60 public static function newFromID( $id ) {
61 $t = Title::newFromID( $id );
62 return $t == null ? null : new Article( $t );
63 }
64
65 /**
66 * Tell the page view functions that this view was redirected
67 * from another page on the wiki.
68 * @param $from Title object.
69 */
70 public function setRedirectedFrom( $from ) {
71 $this->mRedirectedFrom = $from;
72 }
73
74 /**
75 * If this page is a redirect, get its target
76 *
77 * The target will be fetched from the redirect table if possible.
78 * If this page doesn't have an entry there, call insertRedirect()
79 * @return mixed Title object, or null if this page is not a redirect
80 */
81 public function getRedirectTarget() {
82 if( !$this->mTitle || !$this->mTitle->isRedirect() )
83 return null;
84 if( !is_null($this->mRedirectTarget) )
85 return $this->mRedirectTarget;
86 # Query the redirect table
87 $dbr = wfGetDB( DB_SLAVE );
88 $row = $dbr->selectRow( 'redirect',
89 array('rd_namespace', 'rd_title'),
90 array('rd_from' => $this->getID() ),
91 __METHOD__
92 );
93 if( $row ) {
94 return $this->mRedirectTarget = Title::makeTitle($row->rd_namespace, $row->rd_title);
95 }
96 # This page doesn't have an entry in the redirect table
97 return $this->mRedirectTarget = $this->insertRedirect();
98 }
99
100 /**
101 * Insert an entry for this page into the redirect table.
102 *
103 * Don't call this function directly unless you know what you're doing.
104 * @return Title object
105 */
106 public function insertRedirect() {
107 $retval = Title::newFromRedirect( $this->getContent() );
108 if( !$retval ) {
109 return null;
110 }
111 $dbw = wfGetDB( DB_MASTER );
112 $dbw->replace( 'redirect', array('rd_from'),
113 array(
114 'rd_from' => $this->getID(),
115 'rd_namespace' => $retval->getNamespace(),
116 'rd_title' => $retval->getDBkey()
117 ),
118 __METHOD__
119 );
120 return $retval;
121 }
122
123 /**
124 * Get the Title object this page redirects to
125 *
126 * @return mixed false, Title of in-wiki target, or string with URL
127 */
128 public function followRedirect() {
129 $text = $this->getContent();
130 return $this->followRedirectText( $text );
131 }
132
133 /**
134 * Get the Title object this text redirects to
135 *
136 * @return mixed false, Title of in-wiki target, or string with URL
137 */
138 public function followRedirectText( $text ) {
139 $rt = Title::newFromRedirectRecurse( $text ); // recurse through to only get the final target
140 # process if title object is valid and not special:userlogout
141 if( $rt ) {
142 if( $rt->getInterwiki() != '' ) {
143 if( $rt->isLocal() ) {
144 // Offsite wikis need an HTTP redirect.
145 //
146 // This can be hard to reverse and may produce loops,
147 // so they may be disabled in the site configuration.
148 $source = $this->mTitle->getFullURL( 'redirect=no' );
149 return $rt->getFullURL( 'rdfrom=' . urlencode( $source ) );
150 }
151 } else {
152 if( $rt->getNamespace() == NS_SPECIAL ) {
153 // Gotta handle redirects to special pages differently:
154 // Fill the HTTP response "Location" header and ignore
155 // the rest of the page we're on.
156 //
157 // This can be hard to reverse, so they may be disabled.
158 if( $rt->isSpecial( 'Userlogout' ) ) {
159 // rolleyes
160 } else {
161 return $rt->getFullURL();
162 }
163 }
164 return $rt;
165 }
166 }
167 // No or invalid redirect
168 return false;
169 }
170
171 /**
172 * get the title object of the article
173 */
174 public function getTitle() {
175 return $this->mTitle;
176 }
177
178 /**
179 * Clear the object
180 * @private
181 */
182 public function clear() {
183 $this->mDataLoaded = false;
184 $this->mContentLoaded = false;
185
186 $this->mCurID = $this->mUser = $this->mCounter = -1; # Not loaded
187 $this->mRedirectedFrom = null; # Title object if set
188 $this->mRedirectTarget = null; # Title object if set
189 $this->mUserText =
190 $this->mTimestamp = $this->mComment = '';
191 $this->mGoodAdjustment = $this->mTotalAdjustment = 0;
192 $this->mTouched = '19700101000000';
193 $this->mForUpdate = false;
194 $this->mIsRedirect = false;
195 $this->mRevIdFetched = 0;
196 $this->mRedirectUrl = false;
197 $this->mLatest = false;
198 $this->mPreparedEdit = false;
199 }
200
201 /**
202 * Note that getContent/loadContent do not follow redirects anymore.
203 * If you need to fetch redirectable content easily, try
204 * the shortcut in Article::followContent()
205 *
206 * @return Return the text of this revision
207 */
208 public function getContent() {
209 global $wgUser, $wgContLang, $wgOut, $wgMessageCache;
210 wfProfileIn( __METHOD__ );
211 if( $this->getID() === 0 ) {
212 # If this is a MediaWiki:x message, then load the messages
213 # and return the message value for x.
214 if( $this->mTitle->getNamespace() == NS_MEDIAWIKI ) {
215 # If this is a system message, get the default text.
216 list( $message, $lang ) = $wgMessageCache->figureMessage( $wgContLang->lcfirst( $this->mTitle->getText() ) );
217 $wgMessageCache->loadAllMessages( $lang );
218 $text = wfMsgGetKey( $message, false, $lang, false );
219 if( wfEmptyMsg( $message, $text ) )
220 $text = '';
221 } else {
222 $text = wfMsgExt( $wgUser->isLoggedIn() ? 'noarticletext' : 'noarticletextanon', 'parsemag' );
223 }
224 wfProfileOut( __METHOD__ );
225 return $text;
226 } else {
227 $this->loadContent();
228 wfProfileOut( __METHOD__ );
229 return $this->mContent;
230 }
231 }
232
233 /**
234 * Get the text of the current revision. No side-effects...
235 *
236 * @return Return the text of the current revision
237 */
238 public function getRawText() {
239 // Check process cache for current revision
240 if( $this->mContentLoaded && $this->mOldId == 0 ) {
241 return $this->mContent;
242 }
243 $rev = Revision::newFromTitle( $this->mTitle );
244 $text = $rev ? $rev->getRawText() : false;
245 return $text;
246 }
247
248 /**
249 * This function returns the text of a section, specified by a number ($section).
250 * A section is text under a heading like == Heading == or \<h1\>Heading\</h1\>, or
251 * the first section before any such heading (section 0).
252 *
253 * If a section contains subsections, these are also returned.
254 *
255 * @param $text String: text to look in
256 * @param $section Integer: section number
257 * @return string text of the requested section
258 * @deprecated
259 */
260 public function getSection( $text, $section ) {
261 global $wgParser;
262 return $wgParser->getSection( $text, $section );
263 }
264
265 /**
266 * Get the text that needs to be saved in order to undo all revisions
267 * between $undo and $undoafter. Revisions must belong to the same page,
268 * must exist and must not be deleted
269 * @param $undo Revision
270 * @param $undoafter Revision Must be an earlier revision than $undo
271 * @return mixed string on success, false on failure
272 */
273 public function getUndoText( Revision $undo, Revision $undoafter = null ) {
274 $undo_text = $undo->getText();
275 $undoafter_text = $undoafter->getText();
276 $cur_text = $this->getContent();
277 if ( $cur_text == $undo_text ) {
278 # No use doing a merge if it's just a straight revert.
279 return $undoafter_text;
280 }
281 $undone_text = '';
282 if ( !wfMerge( $undo_text, $undoafter_text, $cur_text, $undone_text ) )
283 return false;
284 return $undone_text;
285 }
286
287 /**
288 * @return int The oldid of the article that is to be shown, 0 for the
289 * current revision
290 */
291 public function getOldID() {
292 if( is_null( $this->mOldId ) ) {
293 $this->mOldId = $this->getOldIDFromRequest();
294 }
295 return $this->mOldId;
296 }
297
298 /**
299 * Sets $this->mRedirectUrl to a correct URL if the query parameters are incorrect
300 *
301 * @return int The old id for the request
302 */
303 public function getOldIDFromRequest() {
304 global $wgRequest;
305 $this->mRedirectUrl = false;
306 $oldid = $wgRequest->getVal( 'oldid' );
307 if( isset( $oldid ) ) {
308 $oldid = intval( $oldid );
309 if( $wgRequest->getVal( 'direction' ) == 'next' ) {
310 $nextid = $this->mTitle->getNextRevisionID( $oldid );
311 if( $nextid ) {
312 $oldid = $nextid;
313 } else {
314 $this->mRedirectUrl = $this->mTitle->getFullURL( 'redirect=no' );
315 }
316 } elseif( $wgRequest->getVal( 'direction' ) == 'prev' ) {
317 $previd = $this->mTitle->getPreviousRevisionID( $oldid );
318 if( $previd ) {
319 $oldid = $previd;
320 }
321 }
322 }
323 if( !$oldid ) {
324 $oldid = 0;
325 }
326 return $oldid;
327 }
328
329 /**
330 * Load the revision (including text) into this object
331 */
332 function loadContent() {
333 if( $this->mContentLoaded ) return;
334 wfProfileIn( __METHOD__ );
335 # Query variables :P
336 $oldid = $this->getOldID();
337 # Pre-fill content with error message so that if something
338 # fails we'll have something telling us what we intended.
339 $this->mOldId = $oldid;
340 $this->fetchContent( $oldid );
341 wfProfileOut( __METHOD__ );
342 }
343
344
345 /**
346 * Fetch a page record with the given conditions
347 * @param $dbr Database object
348 * @param $conditions Array
349 */
350 protected function pageData( $dbr, $conditions ) {
351 $fields = array(
352 'page_id',
353 'page_namespace',
354 'page_title',
355 'page_restrictions',
356 'page_counter',
357 'page_is_redirect',
358 'page_is_new',
359 'page_random',
360 'page_touched',
361 'page_latest',
362 'page_len',
363 );
364 wfRunHooks( 'ArticlePageDataBefore', array( &$this, &$fields ) );
365 $row = $dbr->selectRow(
366 'page',
367 $fields,
368 $conditions,
369 __METHOD__
370 );
371 wfRunHooks( 'ArticlePageDataAfter', array( &$this, &$row ) );
372 return $row ;
373 }
374
375 /**
376 * @param $dbr Database object
377 * @param $title Title object
378 */
379 public function pageDataFromTitle( $dbr, $title ) {
380 return $this->pageData( $dbr, array(
381 'page_namespace' => $title->getNamespace(),
382 'page_title' => $title->getDBkey() ) );
383 }
384
385 /**
386 * @param $dbr Database
387 * @param $id Integer
388 */
389 protected function pageDataFromId( $dbr, $id ) {
390 return $this->pageData( $dbr, array( 'page_id' => $id ) );
391 }
392
393 /**
394 * Set the general counter, title etc data loaded from
395 * some source.
396 *
397 * @param $data Database row object or "fromdb"
398 */
399 public function loadPageData( $data = 'fromdb' ) {
400 if( $data === 'fromdb' ) {
401 $dbr = wfGetDB( DB_MASTER );
402 $data = $this->pageDataFromId( $dbr, $this->getId() );
403 }
404
405 $lc = LinkCache::singleton();
406 if( $data ) {
407 $lc->addGoodLinkObj( $data->page_id, $this->mTitle, $data->page_len, $data->page_is_redirect );
408
409 $this->mTitle->mArticleID = $data->page_id;
410
411 # Old-fashioned restrictions
412 $this->mTitle->loadRestrictions( $data->page_restrictions );
413
414 $this->mCounter = $data->page_counter;
415 $this->mTouched = wfTimestamp( TS_MW, $data->page_touched );
416 $this->mIsRedirect = $data->page_is_redirect;
417 $this->mLatest = $data->page_latest;
418 } else {
419 if( is_object( $this->mTitle ) ) {
420 $lc->addBadLinkObj( $this->mTitle );
421 }
422 $this->mTitle->mArticleID = 0;
423 }
424
425 $this->mDataLoaded = true;
426 }
427
428 /**
429 * Get text of an article from database
430 * Does *NOT* follow redirects.
431 * @param $oldid Int: 0 for whatever the latest revision is
432 * @return string
433 */
434 function fetchContent( $oldid = 0 ) {
435 if( $this->mContentLoaded ) {
436 return $this->mContent;
437 }
438
439 $dbr = wfGetDB( DB_MASTER );
440
441 # Pre-fill content with error message so that if something
442 # fails we'll have something telling us what we intended.
443 $t = $this->mTitle->getPrefixedText();
444 $d = $oldid ? wfMsgExt( 'missingarticle-rev', array( 'escape' ), $oldid ) : '';
445 $this->mContent = wfMsg( 'missing-article', $t, $d ) ;
446
447 if( $oldid ) {
448 $revision = Revision::newFromId( $oldid );
449 if( is_null( $revision ) ) {
450 wfDebug( __METHOD__." failed to retrieve specified revision, id $oldid\n" );
451 return false;
452 }
453 $data = $this->pageDataFromId( $dbr, $revision->getPage() );
454 if( !$data ) {
455 wfDebug( __METHOD__." failed to get page data linked to revision id $oldid\n" );
456 return false;
457 }
458 $this->mTitle = Title::makeTitle( $data->page_namespace, $data->page_title );
459 $this->loadPageData( $data );
460 } else {
461 if( !$this->mDataLoaded ) {
462 $data = $this->pageDataFromTitle( $dbr, $this->mTitle );
463 if( !$data ) {
464 wfDebug( __METHOD__." failed to find page data for title " . $this->mTitle->getPrefixedText() . "\n" );
465 return false;
466 }
467 $this->loadPageData( $data );
468 }
469 $revision = Revision::newFromId( $this->mLatest );
470 if( is_null( $revision ) ) {
471 wfDebug( __METHOD__." failed to retrieve current page, rev_id {$this->mLatest}\n" );
472 return false;
473 }
474 }
475
476 // FIXME: Horrible, horrible! This content-loading interface just plain sucks.
477 // We should instead work with the Revision object when we need it...
478 $this->mContent = $revision->getText( Revision::FOR_THIS_USER ); // Loads if user is allowed
479
480 $this->mUser = $revision->getUser();
481 $this->mUserText = $revision->getUserText();
482 $this->mComment = $revision->getComment();
483 $this->mTimestamp = wfTimestamp( TS_MW, $revision->getTimestamp() );
484
485 $this->mRevIdFetched = $revision->getId();
486 $this->mContentLoaded = true;
487 $this->mRevision =& $revision;
488
489 wfRunHooks( 'ArticleAfterFetchContent', array( &$this, &$this->mContent ) ) ;
490
491 return $this->mContent;
492 }
493
494 /**
495 * Read/write accessor to select FOR UPDATE
496 *
497 * @param $x Mixed: FIXME
498 */
499 public function forUpdate( $x = NULL ) {
500 return wfSetVar( $this->mForUpdate, $x );
501 }
502
503 /**
504 * Get the database which should be used for reads
505 *
506 * @return Database
507 * @deprecated - just call wfGetDB( DB_MASTER ) instead
508 */
509 function getDB() {
510 wfDeprecated( __METHOD__ );
511 return wfGetDB( DB_MASTER );
512 }
513
514 /**
515 * Get options for all SELECT statements
516 *
517 * @param $options Array: an optional options array which'll be appended to
518 * the default
519 * @return Array: options
520 */
521 protected function getSelectOptions( $options = '' ) {
522 if( $this->mForUpdate ) {
523 if( is_array( $options ) ) {
524 $options[] = 'FOR UPDATE';
525 } else {
526 $options = 'FOR UPDATE';
527 }
528 }
529 return $options;
530 }
531
532 /**
533 * @return int Page ID
534 */
535 public function getID() {
536 if( $this->mTitle ) {
537 return $this->mTitle->getArticleID();
538 } else {
539 return 0;
540 }
541 }
542
543 /**
544 * @return bool Whether or not the page exists in the database
545 */
546 public function exists() {
547 return $this->getId() > 0;
548 }
549
550 /**
551 * Check if this page is something we're going to be showing
552 * some sort of sensible content for. If we return false, page
553 * views (plain action=view) will return an HTTP 404 response,
554 * so spiders and robots can know they're following a bad link.
555 *
556 * @return bool
557 */
558 public function hasViewableContent() {
559 return $this->exists() || $this->mTitle->isAlwaysKnown();
560 }
561
562 /**
563 * @return int The view count for the page
564 */
565 public function getCount() {
566 if( -1 == $this->mCounter ) {
567 $id = $this->getID();
568 if( $id == 0 ) {
569 $this->mCounter = 0;
570 } else {
571 $dbr = wfGetDB( DB_SLAVE );
572 $this->mCounter = $dbr->selectField( 'page',
573 'page_counter',
574 array( 'page_id' => $id ),
575 __METHOD__,
576 $this->getSelectOptions()
577 );
578 }
579 }
580 return $this->mCounter;
581 }
582
583 /**
584 * Determine whether a page would be suitable for being counted as an
585 * article in the site_stats table based on the title & its content
586 *
587 * @param $text String: text to analyze
588 * @return bool
589 */
590 public function isCountable( $text ) {
591 global $wgUseCommaCount;
592
593 $token = $wgUseCommaCount ? ',' : '[[';
594 return $this->mTitle->isContentPage() && !$this->isRedirect($text) && in_string($token,$text);
595 }
596
597 /**
598 * Tests if the article text represents a redirect
599 *
600 * @param $text String: FIXME
601 * @return bool
602 */
603 public function isRedirect( $text = false ) {
604 if( $text === false ) {
605 if( $this->mDataLoaded ) {
606 return $this->mIsRedirect;
607 }
608 // Apparently loadPageData was never called
609 $this->loadContent();
610 $titleObj = Title::newFromRedirectRecurse( $this->fetchContent() );
611 } else {
612 $titleObj = Title::newFromRedirect( $text );
613 }
614 return $titleObj !== NULL;
615 }
616
617 /**
618 * Returns true if the currently-referenced revision is the current edit
619 * to this page (and it exists).
620 * @return bool
621 */
622 public function isCurrent() {
623 # If no oldid, this is the current version.
624 if( $this->getOldID() == 0 ) {
625 return true;
626 }
627 return $this->exists() && isset($this->mRevision) && $this->mRevision->isCurrent();
628 }
629
630 /**
631 * Loads everything except the text
632 * This isn't necessary for all uses, so it's only done if needed.
633 */
634 protected function loadLastEdit() {
635 if( -1 != $this->mUser )
636 return;
637
638 # New or non-existent articles have no user information
639 $id = $this->getID();
640 if( 0 == $id ) return;
641
642 $this->mLastRevision = Revision::loadFromPageId( wfGetDB( DB_MASTER ), $id );
643 if( !is_null( $this->mLastRevision ) ) {
644 $this->mUser = $this->mLastRevision->getUser();
645 $this->mUserText = $this->mLastRevision->getUserText();
646 $this->mTimestamp = $this->mLastRevision->getTimestamp();
647 $this->mComment = $this->mLastRevision->getComment();
648 $this->mMinorEdit = $this->mLastRevision->isMinor();
649 $this->mRevIdFetched = $this->mLastRevision->getId();
650 }
651 }
652
653 public function getTimestamp() {
654 // Check if the field has been filled by ParserCache::get()
655 if( !$this->mTimestamp ) {
656 $this->loadLastEdit();
657 }
658 return wfTimestamp(TS_MW, $this->mTimestamp);
659 }
660
661 public function getUser() {
662 $this->loadLastEdit();
663 return $this->mUser;
664 }
665
666 public function getUserText() {
667 $this->loadLastEdit();
668 return $this->mUserText;
669 }
670
671 public function getComment() {
672 $this->loadLastEdit();
673 return $this->mComment;
674 }
675
676 public function getMinorEdit() {
677 $this->loadLastEdit();
678 return $this->mMinorEdit;
679 }
680
681 /* Use this to fetch the rev ID used on page views */
682 public function getRevIdFetched() {
683 $this->loadLastEdit();
684 return $this->mRevIdFetched;
685 }
686
687 /**
688 * @param $limit Integer: default 0.
689 * @param $offset Integer: default 0.
690 */
691 public function getContributors($limit = 0, $offset = 0) {
692 # XXX: this is expensive; cache this info somewhere.
693
694 $contribs = array();
695 $dbr = wfGetDB( DB_SLAVE );
696 $revTable = $dbr->tableName( 'revision' );
697 $userTable = $dbr->tableName( 'user' );
698 $user = $this->getUser();
699 $pageId = $this->getId();
700
701 $deletedBit = $dbr->bitAnd('rev_deleted', Revision::DELETED_USER); // username hidden?
702
703 $sql = "SELECT {$userTable}.*, MAX(rev_timestamp) as timestamp
704 FROM $revTable LEFT JOIN $userTable ON rev_user = user_id
705 WHERE rev_page = $pageId
706 AND rev_user != $user
707 AND $deletedBit = 0
708 GROUP BY rev_user, rev_user_text, user_real_name
709 ORDER BY timestamp DESC";
710
711 if($limit > 0)
712 $sql = $dbr->limitResult($sql, $limit, $offset);
713
714 $sql .= ' '. $this->getSelectOptions();
715
716 $res = $dbr->query($sql, __METHOD__ );
717
718 return new UserArrayFromResult( $res );
719 }
720
721 /**
722 * This is the default action of the index.php entry point: just view the
723 * page of the given title.
724 */
725 public function view() {
726 global $wgUser, $wgOut, $wgRequest, $wgContLang;
727 global $wgEnableParserCache, $wgStylePath, $wgParser;
728 global $wgUseTrackbacks;
729
730 wfProfileIn( __METHOD__ );
731
732 # Get variables from query string
733 $oldid = $this->getOldID();
734 $parserCache = ParserCache::singleton();
735
736 $parserOptions = clone $this->getParserOptions();
737 # Render printable version, use printable version cache
738 if ( $wgOut->isPrintable() ) {
739 $parserOptions->setIsPrintable( true );
740 }
741
742 # Try client and file cache
743 if( $oldid === 0 && $this->checkTouched() ) {
744 global $wgUseETag;
745 if( $wgUseETag ) {
746 $wgOut->setETag( $parserCache->getETag( $this, $parserOptions ) );
747 }
748 # Is is client cached?
749 if( $wgOut->checkLastModified( $this->getTouched() ) ) {
750 wfDebug( __METHOD__.": done 304\n" );
751 wfProfileOut( __METHOD__ );
752 return;
753 # Try file cache
754 } else if( $this->tryFileCache() ) {
755 wfDebug( __METHOD__.": done file cache\n" );
756 # tell wgOut that output is taken care of
757 $wgOut->disable();
758 $this->viewUpdates();
759 wfProfileOut( __METHOD__ );
760 return;
761 }
762 }
763
764 $sk = $wgUser->getSkin();
765
766 # getOldID may want us to redirect somewhere else
767 if( $this->mRedirectUrl ) {
768 $wgOut->redirect( $this->mRedirectUrl );
769 wfDebug( __METHOD__.": redirecting due to oldid\n" );
770 wfProfileOut( __METHOD__ );
771 return;
772 }
773
774 $wgOut->setArticleFlag( true );
775 $wgOut->setRobotPolicy( $this->getRobotPolicyForView() );
776 # Set page title (may be overridden by DISPLAYTITLE)
777 $wgOut->setPageTitle( $this->mTitle->getPrefixedText() );
778
779 # If we got diff in the query, we want to see a diff page instead of the article.
780 if( !is_null( $wgRequest->getVal( 'diff' ) ) ) {
781 wfDebug( __METHOD__.": showing diff page\n" );
782 $this->showDiffPage();
783 wfProfileOut( __METHOD__ );
784 return;
785 }
786
787 # Should the parser cache be used?
788 $useParserCache = $this->useParserCache( $oldid );
789 wfDebug( 'Article::view using parser cache: ' . ($useParserCache ? 'yes' : 'no' ) . "\n" );
790 if( $wgUser->getOption( 'stubthreshold' ) ) {
791 wfIncrStats( 'pcache_miss_stub' );
792 }
793
794 # For the main page, overwrite the <title> element with the con-
795 # tents of 'pagetitle-view-mainpage' instead of the default (if
796 # that's not empty).
797 if( $this->mTitle->equals( Title::newMainPage() )
798 && wfMsgForContent( 'pagetitle-view-mainpage' ) !== '' )
799 {
800 $wgOut->setHTMLTitle( wfMsgForContent( 'pagetitle-view-mainpage' ) );
801 }
802
803 $wasRedirected = $this->showRedirectedFromHeader();
804 $this->showNamespaceHeader();
805
806 $outputDone = false;
807 wfRunHooks( 'ArticleViewHeader', array( &$this, &$outputDone, &$useParserCache ) );
808
809 # Try the parser cache
810 if( !$outputDone && $useParserCache ) {
811 $parserOutput = $parserCache->get( $this, $parserOptions );
812 if ( $parserOutput !== false ) {
813 wfDebug( __METHOD__.": showing parser cache contents\n" );
814 $wgOut->addParserOutput( $parserOutput );
815 // Ensure that UI elements requiring revision ID have
816 // the correct version information.
817 $wgOut->setRevisionId( $this->mLatest );
818 $outputDone = true;
819 }
820 }
821
822 if ( $outputDone ) {
823 $this->showViewFooter();
824 $this->viewUpdates();
825 wfProfileOut( __METHOD__ );
826 return;
827 }
828
829 $text = $this->getContent();
830 if( $text === false || $this->getID() == 0 ) {
831 wfDebug( __METHOD__.": showing missing article\n" );
832 $this->showMissingArticle();
833 wfProfileOut( __METHOD__ );
834 return;
835 }
836
837 # Another whitelist check in case oldid is altering the title
838 if( !$this->mTitle->userCanRead() ) {
839 wfDebug( __METHOD__.": denied on secondary read check\n" );
840 $wgOut->loginToUse();
841 $wgOut->output();
842 $wgOut->disable();
843 wfProfileOut( __METHOD__ );
844 return;
845 }
846
847 # We're looking at an old revision
848 if( $oldid && !is_null( $this->mRevision ) ) {
849 $this->setOldSubtitle( $oldid );
850 if ( !$this->showDeletedRevisionHeader() ) {
851 wfDebug( __METHOD__.": cannot view deleted revision\n" );
852 wfProfileOut( __METHOD__ );
853 return;
854 }
855
856 if ( $oldid === $this->getLatest() && $this->useParserCache( false ) ) {
857 $parserOutput = $parserCache->get( $this, $parserOptions );
858 if ( $parserOutput ) {
859 wfDebug( __METHOD__.": showing parser cache for current rev permalink\n" );
860 $wgOut->addParserOutput( $parserOutput );
861 $this->showViewFooter();
862 $this->viewUpdates();
863 wfProfileOut( __METHOD__ );
864 return;
865 }
866 }
867 }
868
869 // Ensure that UI elements requiring revision ID have
870 // the correct version information.
871 $wgOut->setRevisionId( $this->getRevIdFetched() );
872
873 // Pages containing custom CSS or JavaScript get special treatment
874 if( $this->mTitle->isCssOrJsPage() || $this->mTitle->isCssJsSubpage() ) {
875 wfDebug( __METHOD__.": showing CSS/JS source\n" );
876 $this->showCssOrJsPage();
877 $outputDone = true;
878 } else if( $rt = Title::newFromRedirectArray( $text ) ) {
879 wfDebug( __METHOD__.": showing redirect=no page\n" );
880 # Viewing a redirect page (e.g. with parameter redirect=no)
881 # Don't append the subtitle if this was an old revision
882 $wgOut->addHTML( $this->viewRedirect( $rt, !$wasRedirected && $this->isCurrent() ) );
883 # Parse just to get categories, displaytitle, etc.
884 $parserOutput = $wgParser->parse( $text, $this->mTitle, $parserOptions );
885 $wgOut->addParserOutputNoText( $parserOutput );
886 $outputDone = true;
887 }
888 if ( $outputDone ) {
889 $this->showViewFooter();
890 $this->viewUpdates();
891 wfProfileOut( __METHOD__ );
892 return;
893 }
894
895 # Run the parse, protected by a pool counter
896 wfDebug( __METHOD__.": doing uncached parse\n" );
897 $key = $parserCache->getKey( $this, $parserOptions );
898 $poolCounter = PoolCounter::factory( 'Article::view', $key );
899 $dirtyCallback = $useParserCache ? array( $this, 'tryDirtyCache' ) : false;
900 $status = $poolCounter->executeProtected( array( $this, 'doViewParse' ), $dirtyCallback );
901
902 if ( !$status->isOK() ) {
903 # Connection or timeout error
904 $this->showPoolError( $status );
905 wfProfileOut( __METHOD__ );
906 return;
907 }
908
909 $this->showViewFooter();
910 $this->viewUpdates();
911 wfProfileOut( __METHOD__ );
912 }
913
914 /**
915 * Show a diff page according to current request variables. For use within
916 * Article::view() only, other callers should use the DifferenceEngine class.
917 */
918 public function showDiffPage() {
919 global $wgOut, $wgRequest, $wgUser;
920
921 $diff = $wgRequest->getVal( 'diff' );
922 $rcid = $wgRequest->getVal( 'rcid' );
923 $diffOnly = $wgRequest->getBool( 'diffonly', $wgUser->getOption( 'diffonly' ) );
924 $purge = $wgRequest->getVal( 'action' ) == 'purge';
925 $htmldiff = $wgRequest->getVal( 'htmldiff' , false);
926 $unhide = $wgRequest->getInt('unhide') == 1;
927 $oldid = $this->getOldID();
928
929 $de = new DifferenceEngine( $this->mTitle, $oldid, $diff, $rcid, $purge, $htmldiff, $unhide );
930 // DifferenceEngine directly fetched the revision:
931 $this->mRevIdFetched = $de->mNewid;
932 $de->showDiffPage( $diffOnly );
933
934 // Needed to get the page's current revision
935 $this->loadPageData();
936 if( $diff == 0 || $diff == $this->mLatest ) {
937 # Run view updates for current revision only
938 $this->viewUpdates();
939 }
940 }
941
942 /**
943 * Show a page view for a page formatted as CSS or JavaScript. To be called by
944 * Article::view() only.
945 *
946 * This is hooked by SyntaxHighlight_GeSHi to do syntax highlighting of these
947 * page views.
948 */
949 public function showCssOrJsPage() {
950 global $wgOut;
951 $wgOut->addHTML( wfMsgExt( 'clearyourcache', 'parse' ) );
952 // Give hooks a chance to customise the output
953 if( wfRunHooks( 'ShowRawCssJs', array( $this->mContent, $this->mTitle, $wgOut ) ) ) {
954 // Wrap the whole lot in a <pre> and don't parse
955 $m = array();
956 preg_match( '!\.(css|js)$!u', $this->mTitle->getText(), $m );
957 $wgOut->addHTML( "<pre class=\"mw-code mw-{$m[1]}\" dir=\"ltr\">\n" );
958 $wgOut->addHTML( htmlspecialchars( $this->mContent ) );
959 $wgOut->addHTML( "\n</pre>\n" );
960 }
961 }
962
963 /**
964 * Get the robot policy to be used for the current action=view request.
965 */
966 public function getRobotPolicyForView() {
967 global $wgOut, $wgArticleRobotPolicies, $wgNamespaceRobotPolicies;
968 global $wgDefaultRobotPolicy, $wgRequest;
969
970 $ns = $this->mTitle->getNamespace();
971 if( $ns == NS_USER || $ns == NS_USER_TALK ) {
972 # Don't index user and user talk pages for blocked users (bug 11443)
973 if( !$this->mTitle->isSubpage() ) {
974 $block = new Block();
975 if( $block->load( $this->mTitle->getText() ) ) {
976 return 'noindex,nofollow';
977 }
978 }
979 }
980
981 if( $this->getID() === 0 || $this->getOldID() ) {
982 return 'noindex,nofollow';
983 } elseif( $wgOut->isPrintable() ) {
984 # Discourage indexing of printable versions, but encourage following
985 return 'noindex,follow';
986 } elseif( $wgRequest->getInt('curid') ) {
987 # For ?curid=x urls, disallow indexing
988 return 'noindex,follow';
989 } elseif( isset( $wgArticleRobotPolicies[$this->mTitle->getPrefixedText()] ) ) {
990 return $wgArticleRobotPolicies[$this->mTitle->getPrefixedText()];
991 } elseif( isset( $wgNamespaceRobotPolicies[$ns] ) ) {
992 # Honour customised robot policies for this namespace
993 return $wgNamespaceRobotPolicies[$ns];
994 } else {
995 return $wgDefaultRobotPolicy;
996 }
997 }
998
999 /**
1000 * If this request is a redirect view, send "redirected from" subtitle to
1001 * $wgOut. Returns true if the header was needed, false if this is not a
1002 * redirect view. Handles both local and remote redirects.
1003 */
1004 public function showRedirectedFromHeader() {
1005 global $wgOut, $wgUser, $wgRequest, $wgRedirectSources;
1006
1007 $rdfrom = $wgRequest->getVal( 'rdfrom' );
1008 $sk = $wgUser->getSkin();
1009 if( isset( $this->mRedirectedFrom ) ) {
1010 // This is an internally redirected page view.
1011 // We'll need a backlink to the source page for navigation.
1012 if( wfRunHooks( 'ArticleViewRedirect', array( &$this ) ) ) {
1013 $redir = $sk->link(
1014 $this->mRedirectedFrom,
1015 null,
1016 array(),
1017 array( 'redirect' => 'no' ),
1018 array( 'known', 'noclasses' )
1019 );
1020 $s = wfMsgExt( 'redirectedfrom', array( 'parseinline', 'replaceafter' ), $redir );
1021 $wgOut->setSubtitle( $s );
1022
1023 // Set the fragment if one was specified in the redirect
1024 if( strval( $this->mTitle->getFragment() ) != '' ) {
1025 $fragment = Xml::escapeJsString( $this->mTitle->getFragmentForURL() );
1026 $wgOut->addInlineScript( "redirectToFragment(\"$fragment\");" );
1027 }
1028
1029 // Add a <link rel="canonical"> tag
1030 $wgOut->addLink( array( 'rel' => 'canonical',
1031 'href' => $this->mTitle->getLocalURL() )
1032 );
1033 return true;
1034 }
1035 } elseif( $rdfrom ) {
1036 // This is an externally redirected view, from some other wiki.
1037 // If it was reported from a trusted site, supply a backlink.
1038 if( $wgRedirectSources && preg_match( $wgRedirectSources, $rdfrom ) ) {
1039 $redir = $sk->makeExternalLink( $rdfrom, $rdfrom );
1040 $s = wfMsgExt( 'redirectedfrom', array( 'parseinline', 'replaceafter' ), $redir );
1041 $wgOut->setSubtitle( $s );
1042 return true;
1043 }
1044 }
1045 return false;
1046 }
1047
1048 /**
1049 * Show a header specific to the namespace currently being viewed, like
1050 * [[MediaWiki:Talkpagetext]]. For Article::view().
1051 */
1052 public function showNamespaceHeader() {
1053 global $wgOut;
1054 if( $this->mTitle->isTalkPage() ) {
1055 $msg = wfMsgNoTrans( 'talkpageheader' );
1056 if ( $msg !== '-' && !wfEmptyMsg( 'talkpageheader', $msg ) ) {
1057 $wgOut->wrapWikiMsg( "<div class=\"mw-talkpageheader\">\n$1</div>", array( 'talkpageheader' ) );
1058 }
1059 }
1060 }
1061
1062 /**
1063 * Show the footer section of an ordinary page view
1064 */
1065 public function showViewFooter() {
1066 global $wgOut, $wgUseTrackbacks, $wgRequest;
1067 # check if we're displaying a [[User talk:x.x.x.x]] anonymous talk page
1068 if( $this->mTitle->getNamespace() == NS_USER_TALK && IP::isValid( $this->mTitle->getText() ) ) {
1069 $wgOut->addWikiMsg('anontalkpagetext');
1070 }
1071
1072 # If we have been passed an &rcid= parameter, we want to give the user a
1073 # chance to mark this new article as patrolled.
1074 $this->showPatrolFooter();
1075
1076 # Trackbacks
1077 if( $wgUseTrackbacks ) {
1078 $this->addTrackbacks();
1079 }
1080 }
1081
1082 /**
1083 * If patrol is possible, output a patrol UI box. This is called from the
1084 * footer section of ordinary page views. If patrol is not possible or not
1085 * desired, does nothing.
1086 */
1087 public function showPatrolFooter() {
1088 global $wgOut, $wgRequest, $wgUser;
1089 $rcid = $wgRequest->getVal( 'rcid' );
1090
1091 if( !$rcid || !$this->mTitle->exists() || !$this->mTitle->quickUserCan( 'patrol' ) ) {
1092 return;
1093 }
1094
1095 $sk = $wgUser->getSkin();
1096
1097 $wgOut->addHTML(
1098 "<div class='patrollink'>" .
1099 wfMsgHtml(
1100 'markaspatrolledlink',
1101 $sk->link(
1102 $this->mTitle,
1103 wfMsgHtml( 'markaspatrolledtext' ),
1104 array(),
1105 array(
1106 'action' => 'markpatrolled',
1107 'rcid' => $rcid
1108 ),
1109 array( 'known', 'noclasses' )
1110 )
1111 ) .
1112 '</div>'
1113 );
1114 }
1115
1116 /**
1117 * Show the error text for a missing article. For articles in the MediaWiki
1118 * namespace, show the default message text. To be called from Article::view().
1119 */
1120 public function showMissingArticle() {
1121 global $wgOut, $wgRequest;
1122 # Show delete and move logs
1123 $this->showLogs();
1124
1125 # Show error message
1126 $oldid = $this->getOldID();
1127 if( $oldid ) {
1128 $text = wfMsgNoTrans( 'missing-article',
1129 $this->mTitle->getPrefixedText(),
1130 wfMsgNoTrans( 'missingarticle-rev', $oldid ) );
1131 } elseif ( $this->mTitle->getNamespace() === NS_MEDIAWIKI ) {
1132 // Use the default message text
1133 $text = $this->getContent();
1134 } else {
1135 $text = wfMsgNoTrans( 'noarticletext' );
1136 }
1137 $text = "<div class='noarticletext'>\n$text\n</div>";
1138 if( !$this->hasViewableContent() ) {
1139 // If there's no backing content, send a 404 Not Found
1140 // for better machine handling of broken links.
1141 $wgRequest->response()->header( "HTTP/1.x 404 Not Found" );
1142 }
1143 $wgOut->addWikiText( $text );
1144 }
1145
1146 /**
1147 * If the revision requested for view is deleted, check permissions.
1148 * Send either an error message or a warning header to $wgOut.
1149 * Returns true if the view is allowed, false if not.
1150 */
1151 public function showDeletedRevisionHeader() {
1152 global $wgOut, $wgRequest;
1153
1154 if( !$this->mRevision->isDeleted( Revision::DELETED_TEXT ) ) {
1155 // Not deleted
1156 return true;
1157 }
1158
1159 // If the user is not allowed to see it...
1160 if( !$this->mRevision->userCan(Revision::DELETED_TEXT) ) {
1161 $wgOut->wrapWikiMsg( "<div class='mw-warning plainlinks'>\n$1</div>\n",
1162 'rev-deleted-text-permission' );
1163 return false;
1164 // If the user needs to confirm that they want to see it...
1165 } else if( $wgRequest->getInt('unhide') != 1 ) {
1166 # Give explanation and add a link to view the revision...
1167 $oldid = intval( $this->getOldID() );
1168 $link = $this->mTitle->getFullUrl( "oldid={$oldid}&unhide=1" );
1169 $wgOut->wrapWikiMsg( "<div class='mw-warning plainlinks'>\n$1</div>\n",
1170 array('rev-deleted-text-unhide',$link) );
1171 return false;
1172 // We are allowed to see...
1173 } else {
1174 $wgOut->wrapWikiMsg( "<div class='mw-warning plainlinks'>\n$1</div>\n",
1175 'rev-deleted-text-view' );
1176 return true;
1177 }
1178 }
1179
1180 /**
1181 * Show an excerpt from the deletion and move logs. To be called from the
1182 * header section on page views of missing pages.
1183 */
1184 public function showLogs() {
1185 global $wgUser, $wgOut;
1186 $loglist = new LogEventsList( $wgUser->getSkin(), $wgOut );
1187 $pager = new LogPager( $loglist, array('move', 'delete'), false,
1188 $this->mTitle->getPrefixedText(), '', array( "log_action != 'revision'" ) );
1189 if( $pager->getNumRows() > 0 ) {
1190 $pager->mLimit = 10;
1191 $wgOut->addHTML( '<div class="mw-warning-with-logexcerpt">' );
1192 $wgOut->addWikiMsg( 'moveddeleted-notice' );
1193 $wgOut->addHTML(
1194 $loglist->beginLogEventsList() .
1195 $pager->getBody() .
1196 $loglist->endLogEventsList()
1197 );
1198 if( $pager->getNumRows() > 10 ) {
1199 $wgOut->addHTML( $wgUser->getSkin()->link(
1200 SpecialPage::getTitleFor( 'Log' ),
1201 wfMsgHtml( 'log-fulllog' ),
1202 array(),
1203 array( 'page' => $this->mTitle->getPrefixedText() )
1204 ) );
1205 }
1206 $wgOut->addHTML( '</div>' );
1207 }
1208 }
1209
1210 /*
1211 * Should the parser cache be used?
1212 */
1213 public function useParserCache( $oldid ) {
1214 global $wgUser, $wgEnableParserCache;
1215
1216 return $wgEnableParserCache
1217 && intval( $wgUser->getOption( 'stubthreshold' ) ) == 0
1218 && $this->exists()
1219 && empty( $oldid )
1220 && !$this->mTitle->isCssOrJsPage()
1221 && !$this->mTitle->isCssJsSubpage();
1222 }
1223
1224 /**
1225 * Execute the uncached parse for action=view
1226 */
1227 public function doViewParse() {
1228 global $wgOut;
1229 $oldid = $this->getOldID();
1230 $useParserCache = $this->useParserCache( $oldid );
1231 $parserOptions = clone $this->getParserOptions();
1232 # Render printable version, use printable version cache
1233 $parserOptions->setIsPrintable( $wgOut->isPrintable() );
1234 # Don't show section-edit links on old revisions... this way lies madness.
1235 $parserOptions->setEditSection( $this->isCurrent() );
1236 $useParserCache = $this->useParserCache( $oldid );
1237 $this->outputWikiText( $this->getContent(), $useParserCache, $parserOptions );
1238 }
1239
1240 /**
1241 * Try to fetch an expired entry from the parser cache. If it is present,
1242 * output it and return true. If it is not present, output nothing and
1243 * return false. This is used as a callback function for
1244 * PoolCounter::executeProtected().
1245 */
1246 public function tryDirtyCache() {
1247 global $wgOut;
1248 $parserCache = ParserCache::singleton();
1249 $options = $this->getParserOptions();
1250 $options->setIsPrintable( $wgOut->isPrintable() );
1251 $output = $parserCache->getDirty( $this, $options );
1252 if ( $output ) {
1253 wfDebug( __METHOD__.": sending dirty output\n" );
1254 wfDebugLog( 'dirty', "dirty output " . $parserCache->getKey( $this, $options ) . "\n" );
1255 $wgOut->setSquidMaxage( 0 );
1256 $wgOut->addParserOutput( $output );
1257 $wgOut->addHTML( "<!-- parser cache is expired, sending anyway due to pool overload-->\n" );
1258 return true;
1259 } else {
1260 wfDebugLog( 'dirty', "dirty missing\n" );
1261 wfDebug( __METHOD__.": no dirty cache\n" );
1262 return false;
1263 }
1264 }
1265
1266 /**
1267 * Show an error page for an error from the pool counter.
1268 * @param $status Status
1269 */
1270 public function showPoolError( $status ) {
1271 global $wgOut;
1272 $wgOut->clearHTML(); // for release() errors
1273 $wgOut->enableClientCache( false );
1274 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1275 $wgOut->addWikiText(
1276 '<div class="errorbox">' .
1277 $status->getWikiText( false, 'view-pool-error' ) .
1278 '</div>'
1279 );
1280 }
1281
1282 /**
1283 * View redirect
1284 * @param $target Title object or Array of destination(s) to redirect
1285 * @param $appendSubtitle Boolean [optional]
1286 * @param $forceKnown Boolean: should the image be shown as a bluelink regardless of existence?
1287 */
1288 public function viewRedirect( $target, $appendSubtitle = true, $forceKnown = false ) {
1289 global $wgParser, $wgOut, $wgContLang, $wgStylePath, $wgUser;
1290 # Display redirect
1291 if( !is_array( $target ) ) {
1292 $target = array( $target );
1293 }
1294 $imageDir = $wgContLang->isRTL() ? 'rtl' : 'ltr';
1295 $imageUrl = $wgStylePath . '/common/images/redirect' . $imageDir . '.png';
1296 $imageUrl2 = $wgStylePath . '/common/images/nextredirect' . $imageDir . '.png';
1297 $alt2 = $wgContLang->isRTL() ? '&larr;' : '&rarr;'; // should -> and <- be used instead of entities?
1298
1299 if( $appendSubtitle ) {
1300 $wgOut->appendSubtitle( wfMsgHtml( 'redirectpagesub' ) );
1301 }
1302 $sk = $wgUser->getSkin();
1303 // the loop prepends the arrow image before the link, so the first case needs to be outside
1304 $title = array_shift( $target );
1305 if( $forceKnown ) {
1306 $link = $sk->link(
1307 $title,
1308 htmlspecialchars( $title->getFullText() ),
1309 array(),
1310 array(),
1311 array( 'known', 'noclasses' )
1312 );
1313 } else {
1314 $link = $sk->link( $title, htmlspecialchars( $title->getFullText() ) );
1315 }
1316 // automatically append redirect=no to each link, since most of them are redirect pages themselves
1317 foreach( $target as $rt ) {
1318 if( $forceKnown ) {
1319 $link .= '<img src="'.$imageUrl2.'" alt="'.$alt2.' " />'
1320 . $sk->link(
1321 $rt,
1322 htmlspecialchars( $rt->getFullText() ),
1323 array(),
1324 array(),
1325 array( 'known', 'noclasses' )
1326 );
1327 } else {
1328 $link .= '<img src="'.$imageUrl2.'" alt="'.$alt2.' " />'
1329 . $sk->link( $rt, htmlspecialchars( $rt->getFullText() ) );
1330 }
1331 }
1332 return '<img src="'.$imageUrl.'" alt="#REDIRECT " />' .
1333 '<span class="redirectText">'.$link.'</span>';
1334
1335 }
1336
1337 public function addTrackbacks() {
1338 global $wgOut, $wgUser;
1339 $dbr = wfGetDB( DB_SLAVE );
1340 $tbs = $dbr->select( 'trackbacks',
1341 array('tb_id', 'tb_title', 'tb_url', 'tb_ex', 'tb_name'),
1342 array('tb_page' => $this->getID() )
1343 );
1344 if( !$dbr->numRows($tbs) ) return;
1345
1346 $tbtext = "";
1347 while( $o = $dbr->fetchObject($tbs) ) {
1348 $rmvtxt = "";
1349 if( $wgUser->isAllowed( 'trackback' ) ) {
1350 $delurl = $this->mTitle->getFullURL("action=deletetrackback&tbid=" .
1351 $o->tb_id . "&token=" . urlencode( $wgUser->editToken() ) );
1352 $rmvtxt = wfMsg( 'trackbackremove', htmlspecialchars( $delurl ) );
1353 }
1354 $tbtext .= "\n";
1355 $tbtext .= wfMsg(strlen($o->tb_ex) ? 'trackbackexcerpt' : 'trackback',
1356 $o->tb_title,
1357 $o->tb_url,
1358 $o->tb_ex,
1359 $o->tb_name,
1360 $rmvtxt);
1361 }
1362 $wgOut->wrapWikiMsg( "<div id='mw_trackbacks'>$1</div>\n", array( 'trackbackbox', $tbtext ) );
1363 $this->mTitle->invalidateCache();
1364 }
1365
1366 public function deletetrackback() {
1367 global $wgUser, $wgRequest, $wgOut;
1368 if( !$wgUser->matchEditToken($wgRequest->getVal('token')) ) {
1369 $wgOut->addWikiMsg( 'sessionfailure' );
1370 return;
1371 }
1372
1373 $permission_errors = $this->mTitle->getUserPermissionsErrors( 'delete', $wgUser );
1374 if( count($permission_errors) ) {
1375 $wgOut->showPermissionsErrorPage( $permission_errors );
1376 return;
1377 }
1378
1379 $db = wfGetDB( DB_MASTER );
1380 $db->delete( 'trackbacks', array('tb_id' => $wgRequest->getInt('tbid')) );
1381
1382 $wgOut->addWikiMsg( 'trackbackdeleteok' );
1383 $this->mTitle->invalidateCache();
1384 }
1385
1386 public function render() {
1387 global $wgOut;
1388 $wgOut->setArticleBodyOnly(true);
1389 $this->view();
1390 }
1391
1392 /**
1393 * Handle action=purge
1394 */
1395 public function purge() {
1396 global $wgUser, $wgRequest, $wgOut;
1397 if( $wgUser->isAllowed( 'purge' ) || $wgRequest->wasPosted() ) {
1398 if( wfRunHooks( 'ArticlePurge', array( &$this ) ) ) {
1399 $this->doPurge();
1400 $this->view();
1401 }
1402 } else {
1403 $action = htmlspecialchars( $wgRequest->getRequestURL() );
1404 $button = wfMsgExt( 'confirm_purge_button', array('escapenoentities') );
1405 $form = "<form method=\"post\" action=\"$action\">\n" .
1406 "<input type=\"submit\" name=\"submit\" value=\"$button\" />\n" .
1407 "</form>\n";
1408 $top = wfMsgExt( 'confirm-purge-top', array('parse') );
1409 $bottom = wfMsgExt( 'confirm-purge-bottom', array('parse') );
1410 $wgOut->setPageTitle( $this->mTitle->getPrefixedText() );
1411 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1412 $wgOut->addHTML( $top . $form . $bottom );
1413 }
1414 }
1415
1416 /**
1417 * Perform the actions of a page purging
1418 */
1419 public function doPurge() {
1420 global $wgUseSquid;
1421 // Invalidate the cache
1422 $this->mTitle->invalidateCache();
1423
1424 if( $wgUseSquid ) {
1425 // Commit the transaction before the purge is sent
1426 $dbw = wfGetDB( DB_MASTER );
1427 $dbw->immediateCommit();
1428
1429 // Send purge
1430 $update = SquidUpdate::newSimplePurge( $this->mTitle );
1431 $update->doUpdate();
1432 }
1433 if( $this->mTitle->getNamespace() == NS_MEDIAWIKI ) {
1434 global $wgMessageCache;
1435 if( $this->getID() == 0 ) {
1436 $text = false;
1437 } else {
1438 $text = $this->getRawText();
1439 }
1440 $wgMessageCache->replace( $this->mTitle->getDBkey(), $text );
1441 }
1442 }
1443
1444 /**
1445 * Insert a new empty page record for this article.
1446 * This *must* be followed up by creating a revision
1447 * and running $this->updateToLatest( $rev_id );
1448 * or else the record will be left in a funky state.
1449 * Best if all done inside a transaction.
1450 *
1451 * @param $dbw Database
1452 * @return int The newly created page_id key, or false if the title already existed
1453 * @private
1454 */
1455 public function insertOn( $dbw ) {
1456 wfProfileIn( __METHOD__ );
1457
1458 $page_id = $dbw->nextSequenceValue( 'page_page_id_seq' );
1459 $dbw->insert( 'page', array(
1460 'page_id' => $page_id,
1461 'page_namespace' => $this->mTitle->getNamespace(),
1462 'page_title' => $this->mTitle->getDBkey(),
1463 'page_counter' => 0,
1464 'page_restrictions' => '',
1465 'page_is_redirect' => 0, # Will set this shortly...
1466 'page_is_new' => 1,
1467 'page_random' => wfRandom(),
1468 'page_touched' => $dbw->timestamp(),
1469 'page_latest' => 0, # Fill this in shortly...
1470 'page_len' => 0, # Fill this in shortly...
1471 ), __METHOD__, 'IGNORE' );
1472
1473 $affected = $dbw->affectedRows();
1474 if( $affected ) {
1475 $newid = $dbw->insertId();
1476 $this->mTitle->resetArticleId( $newid );
1477 }
1478 wfProfileOut( __METHOD__ );
1479 return $affected ? $newid : false;
1480 }
1481
1482 /**
1483 * Update the page record to point to a newly saved revision.
1484 *
1485 * @param $dbw Database object
1486 * @param $revision Revision: For ID number, and text used to set
1487 length and redirect status fields
1488 * @param $lastRevision Integer: if given, will not overwrite the page field
1489 * when different from the currently set value.
1490 * Giving 0 indicates the new page flag should be set
1491 * on.
1492 * @param $lastRevIsRedirect Boolean: if given, will optimize adding and
1493 * removing rows in redirect table.
1494 * @return bool true on success, false on failure
1495 * @private
1496 */
1497 public function updateRevisionOn( &$dbw, $revision, $lastRevision = null, $lastRevIsRedirect = null ) {
1498 wfProfileIn( __METHOD__ );
1499
1500 $text = $revision->getText();
1501 $rt = Title::newFromRedirect( $text );
1502
1503 $conditions = array( 'page_id' => $this->getId() );
1504 if( !is_null( $lastRevision ) ) {
1505 # An extra check against threads stepping on each other
1506 $conditions['page_latest'] = $lastRevision;
1507 }
1508
1509 $dbw->update( 'page',
1510 array( /* SET */
1511 'page_latest' => $revision->getId(),
1512 'page_touched' => $dbw->timestamp(),
1513 'page_is_new' => ($lastRevision === 0) ? 1 : 0,
1514 'page_is_redirect' => $rt !== NULL ? 1 : 0,
1515 'page_len' => strlen( $text ),
1516 ),
1517 $conditions,
1518 __METHOD__ );
1519
1520 $result = $dbw->affectedRows() != 0;
1521 if( $result ) {
1522 $this->updateRedirectOn( $dbw, $rt, $lastRevIsRedirect );
1523 }
1524
1525 wfProfileOut( __METHOD__ );
1526 return $result;
1527 }
1528
1529 /**
1530 * Add row to the redirect table if this is a redirect, remove otherwise.
1531 *
1532 * @param $dbw Database
1533 * @param $redirectTitle a title object pointing to the redirect target,
1534 * or NULL if this is not a redirect
1535 * @param $lastRevIsRedirect If given, will optimize adding and
1536 * removing rows in redirect table.
1537 * @return bool true on success, false on failure
1538 * @private
1539 */
1540 public function updateRedirectOn( &$dbw, $redirectTitle, $lastRevIsRedirect = null ) {
1541 // Always update redirects (target link might have changed)
1542 // Update/Insert if we don't know if the last revision was a redirect or not
1543 // Delete if changing from redirect to non-redirect
1544 $isRedirect = !is_null($redirectTitle);
1545 if($isRedirect || is_null($lastRevIsRedirect) || $lastRevIsRedirect !== $isRedirect) {
1546 wfProfileIn( __METHOD__ );
1547 if( $isRedirect ) {
1548 // This title is a redirect, Add/Update row in the redirect table
1549 $set = array( /* SET */
1550 'rd_namespace' => $redirectTitle->getNamespace(),
1551 'rd_title' => $redirectTitle->getDBkey(),
1552 'rd_from' => $this->getId(),
1553 );
1554 $dbw->replace( 'redirect', array( 'rd_from' ), $set, __METHOD__ );
1555 } else {
1556 // This is not a redirect, remove row from redirect table
1557 $where = array( 'rd_from' => $this->getId() );
1558 $dbw->delete( 'redirect', $where, __METHOD__);
1559 }
1560 if( $this->getTitle()->getNamespace() == NS_FILE ) {
1561 RepoGroup::singleton()->getLocalRepo()->invalidateImageRedirect( $this->getTitle() );
1562 }
1563 wfProfileOut( __METHOD__ );
1564 return ( $dbw->affectedRows() != 0 );
1565 }
1566 return true;
1567 }
1568
1569 /**
1570 * If the given revision is newer than the currently set page_latest,
1571 * update the page record. Otherwise, do nothing.
1572 *
1573 * @param $dbw Database object
1574 * @param $revision Revision object
1575 */
1576 public function updateIfNewerOn( &$dbw, $revision ) {
1577 wfProfileIn( __METHOD__ );
1578 $row = $dbw->selectRow(
1579 array( 'revision', 'page' ),
1580 array( 'rev_id', 'rev_timestamp', 'page_is_redirect' ),
1581 array(
1582 'page_id' => $this->getId(),
1583 'page_latest=rev_id' ),
1584 __METHOD__ );
1585 if( $row ) {
1586 if( wfTimestamp(TS_MW, $row->rev_timestamp) >= $revision->getTimestamp() ) {
1587 wfProfileOut( __METHOD__ );
1588 return false;
1589 }
1590 $prev = $row->rev_id;
1591 $lastRevIsRedirect = (bool)$row->page_is_redirect;
1592 } else {
1593 # No or missing previous revision; mark the page as new
1594 $prev = 0;
1595 $lastRevIsRedirect = null;
1596 }
1597 $ret = $this->updateRevisionOn( $dbw, $revision, $prev, $lastRevIsRedirect );
1598 wfProfileOut( __METHOD__ );
1599 return $ret;
1600 }
1601
1602 /**
1603 * @param $section empty/null/false or a section number (0, 1, 2, T1, T2...)
1604 * @return string Complete article text, or null if error
1605 */
1606 public function replaceSection( $section, $text, $summary = '', $edittime = NULL ) {
1607 wfProfileIn( __METHOD__ );
1608 if( strval( $section ) == '' ) {
1609 // Whole-page edit; let the whole text through
1610 } else {
1611 if( is_null($edittime) ) {
1612 $rev = Revision::newFromTitle( $this->mTitle );
1613 } else {
1614 $dbw = wfGetDB( DB_MASTER );
1615 $rev = Revision::loadFromTimestamp( $dbw, $this->mTitle, $edittime );
1616 }
1617 if( !$rev ) {
1618 wfDebug( "Article::replaceSection asked for bogus section (page: " .
1619 $this->getId() . "; section: $section; edittime: $edittime)\n" );
1620 return null;
1621 }
1622 $oldtext = $rev->getText();
1623
1624 if( $section == 'new' ) {
1625 # Inserting a new section
1626 $subject = $summary ? wfMsgForContent('newsectionheaderdefaultlevel',$summary) . "\n\n" : '';
1627 $text = strlen( trim( $oldtext ) ) > 0
1628 ? "{$oldtext}\n\n{$subject}{$text}"
1629 : "{$subject}{$text}";
1630 } else {
1631 # Replacing an existing section; roll out the big guns
1632 global $wgParser;
1633 $text = $wgParser->replaceSection( $oldtext, $section, $text );
1634 }
1635 }
1636 wfProfileOut( __METHOD__ );
1637 return $text;
1638 }
1639
1640 /**
1641 * This function is not deprecated until somebody fixes the core not to use
1642 * it. Nevertheless, use Article::doEdit() instead.
1643 */
1644 function insertNewArticle( $text, $summary, $isminor, $watchthis, $suppressRC=false, $comment=false, $bot=false ) {
1645 $flags = EDIT_NEW | EDIT_DEFER_UPDATES | EDIT_AUTOSUMMARY |
1646 ( $isminor ? EDIT_MINOR : 0 ) |
1647 ( $suppressRC ? EDIT_SUPPRESS_RC : 0 ) |
1648 ( $bot ? EDIT_FORCE_BOT : 0 );
1649
1650 # If this is a comment, add the summary as headline
1651 if( $comment && $summary != "" ) {
1652 $text = wfMsgForContent('newsectionheaderdefaultlevel',$summary) . "\n\n".$text;
1653 }
1654
1655 $this->doEdit( $text, $summary, $flags );
1656
1657 $dbw = wfGetDB( DB_MASTER );
1658 if($watchthis) {
1659 if(!$this->mTitle->userIsWatching()) {
1660 $dbw->begin();
1661 $this->doWatch();
1662 $dbw->commit();
1663 }
1664 } else {
1665 if( $this->mTitle->userIsWatching() ) {
1666 $dbw->begin();
1667 $this->doUnwatch();
1668 $dbw->commit();
1669 }
1670 }
1671 $this->doRedirect( $this->isRedirect( $text ) );
1672 }
1673
1674 /**
1675 * @deprecated use Article::doEdit()
1676 */
1677 function updateArticle( $text, $summary, $minor, $watchthis, $forceBot = false, $sectionanchor = '' ) {
1678 $flags = EDIT_UPDATE | EDIT_DEFER_UPDATES | EDIT_AUTOSUMMARY |
1679 ( $minor ? EDIT_MINOR : 0 ) |
1680 ( $forceBot ? EDIT_FORCE_BOT : 0 );
1681
1682 $status = $this->doEdit( $text, $summary, $flags );
1683 if( !$status->isOK() ) {
1684 return false;
1685 }
1686
1687 $dbw = wfGetDB( DB_MASTER );
1688 if( $watchthis ) {
1689 if(!$this->mTitle->userIsWatching()) {
1690 $dbw->begin();
1691 $this->doWatch();
1692 $dbw->commit();
1693 }
1694 } else {
1695 if( $this->mTitle->userIsWatching() ) {
1696 $dbw->begin();
1697 $this->doUnwatch();
1698 $dbw->commit();
1699 }
1700 }
1701
1702 $extraQuery = ''; // Give extensions a chance to modify URL query on update
1703 wfRunHooks( 'ArticleUpdateBeforeRedirect', array( $this, &$sectionanchor, &$extraQuery ) );
1704
1705 $this->doRedirect( $this->isRedirect( $text ), $sectionanchor, $extraQuery );
1706 return true;
1707 }
1708
1709 /**
1710 * Article::doEdit()
1711 *
1712 * Change an existing article or create a new article. Updates RC and all necessary caches,
1713 * optionally via the deferred update array.
1714 *
1715 * $wgUser must be set before calling this function.
1716 *
1717 * @param $text String: new text
1718 * @param $summary String: edit summary
1719 * @param $flags Integer bitfield:
1720 * EDIT_NEW
1721 * Article is known or assumed to be non-existent, create a new one
1722 * EDIT_UPDATE
1723 * Article is known or assumed to be pre-existing, update it
1724 * EDIT_MINOR
1725 * Mark this edit minor, if the user is allowed to do so
1726 * EDIT_SUPPRESS_RC
1727 * Do not log the change in recentchanges
1728 * EDIT_FORCE_BOT
1729 * Mark the edit a "bot" edit regardless of user rights
1730 * EDIT_DEFER_UPDATES
1731 * Defer some of the updates until the end of index.php
1732 * EDIT_AUTOSUMMARY
1733 * Fill in blank summaries with generated text where possible
1734 *
1735 * If neither EDIT_NEW nor EDIT_UPDATE is specified, the status of the article will be detected.
1736 * If EDIT_UPDATE is specified and the article doesn't exist, the function will an
1737 * edit-gone-missing error. If EDIT_NEW is specified and the article does exist, an
1738 * edit-already-exists error will be returned. These two conditions are also possible with
1739 * auto-detection due to MediaWiki's performance-optimised locking strategy.
1740 *
1741 * @param $baseRevId the revision ID this edit was based off, if any
1742 * @param $user Optional user object, $wgUser will be used if not passed
1743 *
1744 * @return Status object. Possible errors:
1745 * edit-hook-aborted: The ArticleSave hook aborted the edit but didn't set the fatal flag of $status
1746 * edit-gone-missing: In update mode, but the article didn't exist
1747 * edit-conflict: In update mode, the article changed unexpectedly
1748 * edit-no-change: Warning that the text was the same as before
1749 * edit-already-exists: In creation mode, but the article already exists
1750 *
1751 * Extensions may define additional errors.
1752 *
1753 * $return->value will contain an associative array with members as follows:
1754 * new: Boolean indicating if the function attempted to create a new article
1755 * revision: The revision object for the inserted revision, or null
1756 *
1757 * Compatibility note: this function previously returned a boolean value indicating success/failure
1758 */
1759 public function doEdit( $text, $summary, $flags = 0, $baseRevId = false, $user = null ) {
1760 global $wgUser, $wgDBtransactions, $wgUseAutomaticEditSummaries;
1761
1762 # Low-level sanity check
1763 if( $this->mTitle->getText() == '' ) {
1764 throw new MWException( 'Something is trying to edit an article with an empty title' );
1765 }
1766
1767 wfProfileIn( __METHOD__ );
1768
1769 $user = is_null($user) ? $wgUser : $user;
1770 $status = Status::newGood( array() );
1771
1772 # Load $this->mTitle->getArticleID() and $this->mLatest if it's not already
1773 $this->loadPageData();
1774
1775 if( !($flags & EDIT_NEW) && !($flags & EDIT_UPDATE) ) {
1776 $aid = $this->mTitle->getArticleID();
1777 if( $aid ) {
1778 $flags |= EDIT_UPDATE;
1779 } else {
1780 $flags |= EDIT_NEW;
1781 }
1782 }
1783
1784 if( !wfRunHooks( 'ArticleSave', array( &$this, &$user, &$text, &$summary,
1785 $flags & EDIT_MINOR, null, null, &$flags, &$status ) ) )
1786 {
1787 wfDebug( __METHOD__ . ": ArticleSave hook aborted save!\n" );
1788 wfProfileOut( __METHOD__ );
1789 if( $status->isOK() ) {
1790 $status->fatal( 'edit-hook-aborted');
1791 }
1792 return $status;
1793 }
1794
1795 # Silently ignore EDIT_MINOR if not allowed
1796 $isminor = ( $flags & EDIT_MINOR ) && $user->isAllowed('minoredit');
1797 $bot = $flags & EDIT_FORCE_BOT;
1798
1799 $oldtext = $this->getRawText(); // current revision
1800 $oldsize = strlen( $oldtext );
1801
1802 # Provide autosummaries if one is not provided and autosummaries are enabled.
1803 if( $wgUseAutomaticEditSummaries && $flags & EDIT_AUTOSUMMARY && $summary == '' ) {
1804 $summary = $this->getAutosummary( $oldtext, $text, $flags );
1805 }
1806
1807 $editInfo = $this->prepareTextForEdit( $text );
1808 $text = $editInfo->pst;
1809 $newsize = strlen( $text );
1810
1811 $dbw = wfGetDB( DB_MASTER );
1812 $now = wfTimestampNow();
1813
1814 if( $flags & EDIT_UPDATE ) {
1815 # Update article, but only if changed.
1816 $status->value['new'] = false;
1817 # Make sure the revision is either completely inserted or not inserted at all
1818 if( !$wgDBtransactions ) {
1819 $userAbort = ignore_user_abort( true );
1820 }
1821
1822 $revisionId = 0;
1823
1824 $changed = ( strcmp( $text, $oldtext ) != 0 );
1825
1826 if( $changed ) {
1827 $this->mGoodAdjustment = (int)$this->isCountable( $text )
1828 - (int)$this->isCountable( $oldtext );
1829 $this->mTotalAdjustment = 0;
1830
1831 if( !$this->mLatest ) {
1832 # Article gone missing
1833 wfDebug( __METHOD__.": EDIT_UPDATE specified but article doesn't exist\n" );
1834 $status->fatal( 'edit-gone-missing' );
1835 wfProfileOut( __METHOD__ );
1836 return $status;
1837 }
1838
1839 $revision = new Revision( array(
1840 'page' => $this->getId(),
1841 'comment' => $summary,
1842 'minor_edit' => $isminor,
1843 'text' => $text,
1844 'parent_id' => $this->mLatest,
1845 'user' => $user->getId(),
1846 'user_text' => $user->getName(),
1847 ) );
1848
1849 $dbw->begin();
1850 $revisionId = $revision->insertOn( $dbw );
1851
1852 # Update page
1853 #
1854 # Note that we use $this->mLatest instead of fetching a value from the master DB
1855 # during the course of this function. This makes sure that EditPage can detect
1856 # edit conflicts reliably, either by $ok here, or by $article->getTimestamp()
1857 # before this function is called. A previous function used a separate query, this
1858 # creates a window where concurrent edits can cause an ignored edit conflict.
1859 $ok = $this->updateRevisionOn( $dbw, $revision, $this->mLatest );
1860
1861 if( !$ok ) {
1862 /* Belated edit conflict! Run away!! */
1863 $status->fatal( 'edit-conflict' );
1864 # Delete the invalid revision if the DB is not transactional
1865 if( !$wgDBtransactions ) {
1866 $dbw->delete( 'revision', array( 'rev_id' => $revisionId ), __METHOD__ );
1867 }
1868 $revisionId = 0;
1869 $dbw->rollback();
1870 } else {
1871 global $wgUseRCPatrol;
1872 wfRunHooks( 'NewRevisionFromEditComplete', array($this, $revision, $baseRevId, $user) );
1873 # Update recentchanges
1874 if( !( $flags & EDIT_SUPPRESS_RC ) ) {
1875 # Mark as patrolled if the user can do so
1876 $patrolled = $wgUseRCPatrol && $this->mTitle->userCan('autopatrol');
1877 # Add RC row to the DB
1878 $rc = RecentChange::notifyEdit( $now, $this->mTitle, $isminor, $user, $summary,
1879 $this->mLatest, $this->getTimestamp(), $bot, '', $oldsize, $newsize,
1880 $revisionId, $patrolled
1881 );
1882 # Log auto-patrolled edits
1883 if( $patrolled ) {
1884 PatrolLog::record( $rc, true );
1885 }
1886 }
1887 $user->incEditCount();
1888 $dbw->commit();
1889 }
1890 } else {
1891 $status->warning( 'edit-no-change' );
1892 $revision = null;
1893 // Keep the same revision ID, but do some updates on it
1894 $revisionId = $this->getRevIdFetched();
1895 // Update page_touched, this is usually implicit in the page update
1896 // Other cache updates are done in onArticleEdit()
1897 $this->mTitle->invalidateCache();
1898 }
1899
1900 if( !$wgDBtransactions ) {
1901 ignore_user_abort( $userAbort );
1902 }
1903 // Now that ignore_user_abort is restored, we can respond to fatal errors
1904 if( !$status->isOK() ) {
1905 wfProfileOut( __METHOD__ );
1906 return $status;
1907 }
1908
1909 # Invalidate cache of this article and all pages using this article
1910 # as a template. Partly deferred.
1911 Article::onArticleEdit( $this->mTitle );
1912 # Update links tables, site stats, etc.
1913 $this->editUpdates( $text, $summary, $isminor, $now, $revisionId, $changed );
1914 } else {
1915 # Create new article
1916 $status->value['new'] = true;
1917
1918 # Set statistics members
1919 # We work out if it's countable after PST to avoid counter drift
1920 # when articles are created with {{subst:}}
1921 $this->mGoodAdjustment = (int)$this->isCountable( $text );
1922 $this->mTotalAdjustment = 1;
1923
1924 $dbw->begin();
1925
1926 # Add the page record; stake our claim on this title!
1927 # This will return false if the article already exists
1928 $newid = $this->insertOn( $dbw );
1929
1930 if( $newid === false ) {
1931 $dbw->rollback();
1932 $status->fatal( 'edit-already-exists' );
1933 wfProfileOut( __METHOD__ );
1934 return $status;
1935 }
1936
1937 # Save the revision text...
1938 $revision = new Revision( array(
1939 'page' => $newid,
1940 'comment' => $summary,
1941 'minor_edit' => $isminor,
1942 'text' => $text,
1943 'user' => $user->getId(),
1944 'user_text' => $user->getName(),
1945 ) );
1946 $revisionId = $revision->insertOn( $dbw );
1947
1948 $this->mTitle->resetArticleID( $newid );
1949
1950 # Update the page record with revision data
1951 $this->updateRevisionOn( $dbw, $revision, 0 );
1952
1953 wfRunHooks( 'NewRevisionFromEditComplete', array($this, $revision, false, $user) );
1954 # Update recentchanges
1955 if( !( $flags & EDIT_SUPPRESS_RC ) ) {
1956 global $wgUseRCPatrol, $wgUseNPPatrol;
1957 # Mark as patrolled if the user can do so
1958 $patrolled = ($wgUseRCPatrol || $wgUseNPPatrol) && $this->mTitle->userCan('autopatrol');
1959 # Add RC row to the DB
1960 $rc = RecentChange::notifyNew( $now, $this->mTitle, $isminor, $user, $summary, $bot,
1961 '', strlen($text), $revisionId, $patrolled );
1962 # Log auto-patrolled edits
1963 if( $patrolled ) {
1964 PatrolLog::record( $rc, true );
1965 }
1966 }
1967 $user->incEditCount();
1968 $dbw->commit();
1969
1970 # Update links, etc.
1971 $this->editUpdates( $text, $summary, $isminor, $now, $revisionId, true );
1972
1973 # Clear caches
1974 Article::onArticleCreate( $this->mTitle );
1975
1976 wfRunHooks( 'ArticleInsertComplete', array( &$this, &$user, $text, $summary,
1977 $flags & EDIT_MINOR, null, null, &$flags, $revision ) );
1978 }
1979
1980 # Do updates right now unless deferral was requested
1981 if( !( $flags & EDIT_DEFER_UPDATES ) ) {
1982 wfDoUpdates();
1983 }
1984
1985 // Return the new revision (or null) to the caller
1986 $status->value['revision'] = $revision;
1987
1988 wfRunHooks( 'ArticleSaveComplete', array( &$this, &$user, $text, $summary,
1989 $flags & EDIT_MINOR, null, null, &$flags, $revision, &$status, $baseRevId ) );
1990
1991 wfProfileOut( __METHOD__ );
1992 return $status;
1993 }
1994
1995 /**
1996 * @deprecated wrapper for doRedirect
1997 */
1998 public function showArticle( $text, $subtitle , $sectionanchor = '', $me2, $now, $summary, $oldid ) {
1999 wfDeprecated( __METHOD__ );
2000 $this->doRedirect( $this->isRedirect( $text ), $sectionanchor );
2001 }
2002
2003 /**
2004 * Output a redirect back to the article.
2005 * This is typically used after an edit.
2006 *
2007 * @param $noRedir Boolean: add redirect=no
2008 * @param $sectionAnchor String: section to redirect to, including "#"
2009 * @param $extraQuery String: extra query params
2010 */
2011 public function doRedirect( $noRedir = false, $sectionAnchor = '', $extraQuery = '' ) {
2012 global $wgOut;
2013 if( $noRedir ) {
2014 $query = 'redirect=no';
2015 if( $extraQuery )
2016 $query .= "&$query";
2017 } else {
2018 $query = $extraQuery;
2019 }
2020 $wgOut->redirect( $this->mTitle->getFullURL( $query ) . $sectionAnchor );
2021 }
2022
2023 /**
2024 * Mark this particular edit/page as patrolled
2025 */
2026 public function markpatrolled() {
2027 global $wgOut, $wgRequest, $wgUseRCPatrol, $wgUseNPPatrol, $wgUser;
2028 $wgOut->setRobotPolicy( 'noindex,nofollow' );
2029
2030 # If we haven't been given an rc_id value, we can't do anything
2031 $rcid = (int) $wgRequest->getVal('rcid');
2032 $rc = RecentChange::newFromId($rcid);
2033 if( is_null($rc) ) {
2034 $wgOut->showErrorPage( 'markedaspatrollederror', 'markedaspatrollederrortext' );
2035 return;
2036 }
2037
2038 #It would be nice to see where the user had actually come from, but for now just guess
2039 $returnto = $rc->getAttribute( 'rc_type' ) == RC_NEW ? 'Newpages' : 'Recentchanges';
2040 $return = SpecialPage::getTitleFor( $returnto );
2041
2042 $dbw = wfGetDB( DB_MASTER );
2043 $errors = $rc->doMarkPatrolled();
2044
2045 if( in_array(array('rcpatroldisabled'), $errors) ) {
2046 $wgOut->showErrorPage( 'rcpatroldisabled', 'rcpatroldisabledtext' );
2047 return;
2048 }
2049
2050 if( in_array(array('hookaborted'), $errors) ) {
2051 // The hook itself has handled any output
2052 return;
2053 }
2054
2055 if( in_array(array('markedaspatrollederror-noautopatrol'), $errors) ) {
2056 $wgOut->setPageTitle( wfMsg( 'markedaspatrollederror' ) );
2057 $wgOut->addWikiMsg( 'markedaspatrollederror-noautopatrol' );
2058 $wgOut->returnToMain( false, $return );
2059 return;
2060 }
2061
2062 if( !empty($errors) ) {
2063 $wgOut->showPermissionsErrorPage( $errors );
2064 return;
2065 }
2066
2067 # Inform the user
2068 $wgOut->setPageTitle( wfMsg( 'markedaspatrolled' ) );
2069 $wgOut->addWikiMsg( 'markedaspatrolledtext' );
2070 $wgOut->returnToMain( false, $return );
2071 }
2072
2073 /**
2074 * User-interface handler for the "watch" action
2075 */
2076
2077 public function watch() {
2078 global $wgUser, $wgOut;
2079 if( $wgUser->isAnon() ) {
2080 $wgOut->showErrorPage( 'watchnologin', 'watchnologintext' );
2081 return;
2082 }
2083 if( wfReadOnly() ) {
2084 $wgOut->readOnlyPage();
2085 return;
2086 }
2087 if( $this->doWatch() ) {
2088 $wgOut->setPagetitle( wfMsg( 'addedwatch' ) );
2089 $wgOut->setRobotPolicy( 'noindex,nofollow' );
2090 $wgOut->addWikiMsg( 'addedwatchtext', $this->mTitle->getPrefixedText() );
2091 }
2092 $wgOut->returnToMain( true, $this->mTitle->getPrefixedText() );
2093 }
2094
2095 /**
2096 * Add this page to $wgUser's watchlist
2097 * @return bool true on successful watch operation
2098 */
2099 public function doWatch() {
2100 global $wgUser;
2101 if( $wgUser->isAnon() ) {
2102 return false;
2103 }
2104 if( wfRunHooks('WatchArticle', array(&$wgUser, &$this)) ) {
2105 $wgUser->addWatch( $this->mTitle );
2106 return wfRunHooks('WatchArticleComplete', array(&$wgUser, &$this));
2107 }
2108 return false;
2109 }
2110
2111 /**
2112 * User interface handler for the "unwatch" action.
2113 */
2114 public function unwatch() {
2115 global $wgUser, $wgOut;
2116 if( $wgUser->isAnon() ) {
2117 $wgOut->showErrorPage( 'watchnologin', 'watchnologintext' );
2118 return;
2119 }
2120 if( wfReadOnly() ) {
2121 $wgOut->readOnlyPage();
2122 return;
2123 }
2124 if( $this->doUnwatch() ) {
2125 $wgOut->setPagetitle( wfMsg( 'removedwatch' ) );
2126 $wgOut->setRobotPolicy( 'noindex,nofollow' );
2127 $wgOut->addWikiMsg( 'removedwatchtext', $this->mTitle->getPrefixedText() );
2128 }
2129 $wgOut->returnToMain( true, $this->mTitle->getPrefixedText() );
2130 }
2131
2132 /**
2133 * Stop watching a page
2134 * @return bool true on successful unwatch
2135 */
2136 public function doUnwatch() {
2137 global $wgUser;
2138 if( $wgUser->isAnon() ) {
2139 return false;
2140 }
2141 if( wfRunHooks('UnwatchArticle', array(&$wgUser, &$this)) ) {
2142 $wgUser->removeWatch( $this->mTitle );
2143 return wfRunHooks('UnwatchArticleComplete', array(&$wgUser, &$this));
2144 }
2145 return false;
2146 }
2147
2148 /**
2149 * action=protect handler
2150 */
2151 public function protect() {
2152 $form = new ProtectionForm( $this );
2153 $form->execute();
2154 }
2155
2156 /**
2157 * action=unprotect handler (alias)
2158 */
2159 public function unprotect() {
2160 $this->protect();
2161 }
2162
2163 /**
2164 * Update the article's restriction field, and leave a log entry.
2165 *
2166 * @param $limit Array: set of restriction keys
2167 * @param $reason String
2168 * @param &$cascade Integer. Set to false if cascading protection isn't allowed.
2169 * @param $expiry Array: per restriction type expiration
2170 * @return bool true on success
2171 */
2172 public function updateRestrictions( $limit = array(), $reason = '', &$cascade = 0, $expiry = array() ) {
2173 global $wgUser, $wgRestrictionTypes, $wgContLang;
2174
2175 $id = $this->mTitle->getArticleID();
2176 if ( $id <= 0 ) {
2177 wfDebug( "updateRestrictions failed: $id <= 0\n" );
2178 return false;
2179 }
2180
2181 if ( wfReadOnly() ) {
2182 wfDebug( "updateRestrictions failed: read-only\n" );
2183 return false;
2184 }
2185
2186 if ( !$this->mTitle->userCan( 'protect' ) ) {
2187 wfDebug( "updateRestrictions failed: insufficient permissions\n" );
2188 return false;
2189 }
2190
2191 if( !$cascade ) {
2192 $cascade = false;
2193 }
2194
2195 // Take this opportunity to purge out expired restrictions
2196 Title::purgeExpiredRestrictions();
2197
2198 # FIXME: Same limitations as described in ProtectionForm.php (line 37);
2199 # we expect a single selection, but the schema allows otherwise.
2200 $current = array();
2201 $updated = Article::flattenRestrictions( $limit );
2202 $changed = false;
2203 foreach( $wgRestrictionTypes as $action ) {
2204 if( isset( $expiry[$action] ) ) {
2205 # Get current restrictions on $action
2206 $aLimits = $this->mTitle->getRestrictions( $action );
2207 $current[$action] = implode( '', $aLimits );
2208 # Are any actual restrictions being dealt with here?
2209 $aRChanged = count($aLimits) || !empty($limit[$action]);
2210 # If something changed, we need to log it. Checking $aRChanged
2211 # assures that "unprotecting" a page that is not protected does
2212 # not log just because the expiry was "changed".
2213 if( $aRChanged && $this->mTitle->mRestrictionsExpiry[$action] != $expiry[$action] ) {
2214 $changed = true;
2215 }
2216 }
2217 }
2218
2219 $current = Article::flattenRestrictions( $current );
2220
2221 $changed = ($changed || $current != $updated );
2222 $changed = $changed || ($updated && $this->mTitle->areRestrictionsCascading() != $cascade);
2223 $protect = ( $updated != '' );
2224
2225 # If nothing's changed, do nothing
2226 if( $changed ) {
2227 if( wfRunHooks( 'ArticleProtect', array( &$this, &$wgUser, $limit, $reason ) ) ) {
2228
2229 $dbw = wfGetDB( DB_MASTER );
2230
2231 # Prepare a null revision to be added to the history
2232 $modified = $current != '' && $protect;
2233 if( $protect ) {
2234 $comment_type = $modified ? 'modifiedarticleprotection' : 'protectedarticle';
2235 } else {
2236 $comment_type = 'unprotectedarticle';
2237 }
2238 $comment = $wgContLang->ucfirst( wfMsgForContent( $comment_type, $this->mTitle->getPrefixedText() ) );
2239
2240 # Only restrictions with the 'protect' right can cascade...
2241 # Otherwise, people who cannot normally protect can "protect" pages via transclusion
2242 $editrestriction = isset( $limit['edit'] ) ? array( $limit['edit'] ) : $this->mTitle->getRestrictions( 'edit' );
2243 # The schema allows multiple restrictions
2244 if(!in_array('protect', $editrestriction) && !in_array('sysop', $editrestriction))
2245 $cascade = false;
2246 $cascade_description = '';
2247 if( $cascade ) {
2248 $cascade_description = ' ['.wfMsgForContent('protect-summary-cascade').']';
2249 }
2250
2251 if( $reason )
2252 $comment .= ": $reason";
2253
2254 $editComment = $comment;
2255 $encodedExpiry = array();
2256 $protect_description = '';
2257 foreach( $limit as $action => $restrictions ) {
2258 if ( !isset($expiry[$action]) )
2259 $expiry[$action] = 'infinite';
2260
2261 $encodedExpiry[$action] = Block::encodeExpiry($expiry[$action], $dbw );
2262 if( $restrictions != '' ) {
2263 $protect_description .= "[$action=$restrictions] (";
2264 if( $encodedExpiry[$action] != 'infinity' ) {
2265 $protect_description .= wfMsgForContent( 'protect-expiring',
2266 $wgContLang->timeanddate( $expiry[$action], false, false ) ,
2267 $wgContLang->date( $expiry[$action], false, false ) ,
2268 $wgContLang->time( $expiry[$action], false, false ) );
2269 } else {
2270 $protect_description .= wfMsgForContent( 'protect-expiry-indefinite' );
2271 }
2272 $protect_description .= ') ';
2273 }
2274 }
2275 $protect_description = trim($protect_description);
2276
2277 if( $protect_description && $protect )
2278 $editComment .= " ($protect_description)";
2279 if( $cascade )
2280 $editComment .= "$cascade_description";
2281 # Update restrictions table
2282 foreach( $limit as $action => $restrictions ) {
2283 if($restrictions != '' ) {
2284 $dbw->replace( 'page_restrictions', array(array('pr_page', 'pr_type')),
2285 array( 'pr_page' => $id,
2286 'pr_type' => $action,
2287 'pr_level' => $restrictions,
2288 'pr_cascade' => ($cascade && $action == 'edit') ? 1 : 0,
2289 'pr_expiry' => $encodedExpiry[$action] ), __METHOD__ );
2290 } else {
2291 $dbw->delete( 'page_restrictions', array( 'pr_page' => $id,
2292 'pr_type' => $action ), __METHOD__ );
2293 }
2294 }
2295
2296 # Insert a null revision
2297 $nullRevision = Revision::newNullRevision( $dbw, $id, $editComment, true );
2298 $nullRevId = $nullRevision->insertOn( $dbw );
2299
2300 $latest = $this->getLatest();
2301 # Update page record
2302 $dbw->update( 'page',
2303 array( /* SET */
2304 'page_touched' => $dbw->timestamp(),
2305 'page_restrictions' => '',
2306 'page_latest' => $nullRevId
2307 ), array( /* WHERE */
2308 'page_id' => $id
2309 ), 'Article::protect'
2310 );
2311
2312 wfRunHooks( 'NewRevisionFromEditComplete', array($this, $nullRevision, $latest, $wgUser) );
2313 wfRunHooks( 'ArticleProtectComplete', array( &$this, &$wgUser, $limit, $reason ) );
2314
2315 # Update the protection log
2316 $log = new LogPage( 'protect' );
2317 if( $protect ) {
2318 $params = array($protect_description,$cascade ? 'cascade' : '');
2319 $log->addEntry( $modified ? 'modify' : 'protect', $this->mTitle, trim( $reason), $params );
2320 } else {
2321 $log->addEntry( 'unprotect', $this->mTitle, $reason );
2322 }
2323
2324 } # End hook
2325 } # End "changed" check
2326
2327 return true;
2328 }
2329
2330 /**
2331 * Take an array of page restrictions and flatten it to a string
2332 * suitable for insertion into the page_restrictions field.
2333 * @param $limit Array
2334 * @return String
2335 */
2336 protected static function flattenRestrictions( $limit ) {
2337 if( !is_array( $limit ) ) {
2338 throw new MWException( 'Article::flattenRestrictions given non-array restriction set' );
2339 }
2340 $bits = array();
2341 ksort( $limit );
2342 foreach( $limit as $action => $restrictions ) {
2343 if( $restrictions != '' ) {
2344 $bits[] = "$action=$restrictions";
2345 }
2346 }
2347 return implode( ':', $bits );
2348 }
2349
2350 /**
2351 * Auto-generates a deletion reason
2352 * @param &$hasHistory Boolean: whether the page has a history
2353 */
2354 public function generateReason( &$hasHistory ) {
2355 global $wgContLang;
2356 $dbw = wfGetDB( DB_MASTER );
2357 // Get the last revision
2358 $rev = Revision::newFromTitle( $this->mTitle );
2359 if( is_null( $rev ) )
2360 return false;
2361
2362 // Get the article's contents
2363 $contents = $rev->getText();
2364 $blank = false;
2365 // If the page is blank, use the text from the previous revision,
2366 // which can only be blank if there's a move/import/protect dummy revision involved
2367 if( $contents == '' ) {
2368 $prev = $rev->getPrevious();
2369 if( $prev ) {
2370 $contents = $prev->getText();
2371 $blank = true;
2372 }
2373 }
2374
2375 // Find out if there was only one contributor
2376 // Only scan the last 20 revisions
2377 $res = $dbw->select( 'revision', 'rev_user_text',
2378 array( 'rev_page' => $this->getID(), $dbw->bitAnd('rev_deleted', Revision::DELETED_USER) . ' = 0' ),
2379 __METHOD__,
2380 array( 'LIMIT' => 20 )
2381 );
2382 if( $res === false )
2383 // This page has no revisions, which is very weird
2384 return false;
2385
2386 $hasHistory = ( $res->numRows() > 1 );
2387 $row = $dbw->fetchObject( $res );
2388 $onlyAuthor = $row->rev_user_text;
2389 // Try to find a second contributor
2390 foreach( $res as $row ) {
2391 if( $row->rev_user_text != $onlyAuthor ) {
2392 $onlyAuthor = false;
2393 break;
2394 }
2395 }
2396 $dbw->freeResult( $res );
2397
2398 // Generate the summary with a '$1' placeholder
2399 if( $blank ) {
2400 // The current revision is blank and the one before is also
2401 // blank. It's just not our lucky day
2402 $reason = wfMsgForContent( 'exbeforeblank', '$1' );
2403 } else {
2404 if( $onlyAuthor )
2405 $reason = wfMsgForContent( 'excontentauthor', '$1', $onlyAuthor );
2406 else
2407 $reason = wfMsgForContent( 'excontent', '$1' );
2408 }
2409
2410 if( $reason == '-' ) {
2411 // Allow these UI messages to be blanked out cleanly
2412 return '';
2413 }
2414
2415 // Replace newlines with spaces to prevent uglyness
2416 $contents = preg_replace( "/[\n\r]/", ' ', $contents );
2417 // Calculate the maximum amount of chars to get
2418 // Max content length = max comment length - length of the comment (excl. $1) - '...'
2419 $maxLength = 255 - (strlen( $reason ) - 2) - 3;
2420 $contents = $wgContLang->truncate( $contents, $maxLength );
2421 // Remove possible unfinished links
2422 $contents = preg_replace( '/\[\[([^\]]*)\]?$/', '$1', $contents );
2423 // Now replace the '$1' placeholder
2424 $reason = str_replace( '$1', $contents, $reason );
2425 return $reason;
2426 }
2427
2428
2429 /*
2430 * UI entry point for page deletion
2431 */
2432 public function delete() {
2433 global $wgUser, $wgOut, $wgRequest;
2434
2435 $confirm = $wgRequest->wasPosted() &&
2436 $wgUser->matchEditToken( $wgRequest->getVal( 'wpEditToken' ) );
2437
2438 $this->DeleteReasonList = $wgRequest->getText( 'wpDeleteReasonList', 'other' );
2439 $this->DeleteReason = $wgRequest->getText( 'wpReason' );
2440
2441 $reason = $this->DeleteReasonList;
2442
2443 if( $reason != 'other' && $this->DeleteReason != '' ) {
2444 // Entry from drop down menu + additional comment
2445 $reason .= wfMsgForContent( 'colon-separator' ) . $this->DeleteReason;
2446 } elseif( $reason == 'other' ) {
2447 $reason = $this->DeleteReason;
2448 }
2449 # Flag to hide all contents of the archived revisions
2450 $suppress = $wgRequest->getVal( 'wpSuppress' ) && $wgUser->isAllowed( 'suppressrevision' );
2451
2452 # This code desperately needs to be totally rewritten
2453
2454 # Read-only check...
2455 if( wfReadOnly() ) {
2456 $wgOut->readOnlyPage();
2457 return;
2458 }
2459
2460 # Check permissions
2461 $permission_errors = $this->mTitle->getUserPermissionsErrors( 'delete', $wgUser );
2462
2463 if( count( $permission_errors ) > 0 ) {
2464 $wgOut->showPermissionsErrorPage( $permission_errors );
2465 return;
2466 }
2467
2468 $wgOut->setPagetitle( wfMsg( 'delete-confirm', $this->mTitle->getPrefixedText() ) );
2469
2470 # Better double-check that it hasn't been deleted yet!
2471 $dbw = wfGetDB( DB_MASTER );
2472 $conds = $this->mTitle->pageCond();
2473 $latest = $dbw->selectField( 'page', 'page_latest', $conds, __METHOD__ );
2474 if( $latest === false ) {
2475 $wgOut->showFatalError( wfMsgExt( 'cannotdelete', array( 'parse' ) ) );
2476 $wgOut->addHTML( Xml::element( 'h2', null, LogPage::logName( 'delete' ) ) );
2477 LogEventsList::showLogExtract( $wgOut, 'delete', $this->mTitle->getPrefixedText() );
2478 return;
2479 }
2480
2481 # Hack for big sites
2482 $bigHistory = $this->isBigDeletion();
2483 if( $bigHistory && !$this->mTitle->userCan( 'bigdelete' ) ) {
2484 global $wgLang, $wgDeleteRevisionsLimit;
2485 $wgOut->wrapWikiMsg( "<div class='error'>\n$1</div>\n",
2486 array( 'delete-toobig', $wgLang->formatNum( $wgDeleteRevisionsLimit ) ) );
2487 return;
2488 }
2489
2490 if( $confirm ) {
2491 $this->doDelete( $reason, $suppress );
2492 if( $wgRequest->getCheck( 'wpWatch' ) ) {
2493 $this->doWatch();
2494 } elseif( $this->mTitle->userIsWatching() ) {
2495 $this->doUnwatch();
2496 }
2497 return;
2498 }
2499
2500 // Generate deletion reason
2501 $hasHistory = false;
2502 if( !$reason ) $reason = $this->generateReason($hasHistory);
2503
2504 // If the page has a history, insert a warning
2505 if( $hasHistory && !$confirm ) {
2506 $skin = $wgUser->getSkin();
2507 $wgOut->addHTML( '<strong>' . wfMsgExt( 'historywarning', array( 'parseinline' ) ) . ' ' . $skin->historyLink() . '</strong>' );
2508 if( $bigHistory ) {
2509 global $wgLang, $wgDeleteRevisionsLimit;
2510 $wgOut->wrapWikiMsg( "<div class='error'>\n$1</div>\n",
2511 array( 'delete-warning-toobig', $wgLang->formatNum( $wgDeleteRevisionsLimit ) ) );
2512 }
2513 }
2514
2515 return $this->confirmDelete( $reason );
2516 }
2517
2518 /**
2519 * @return bool whether or not the page surpasses $wgDeleteRevisionsLimit revisions
2520 */
2521 public function isBigDeletion() {
2522 global $wgDeleteRevisionsLimit;
2523 if( $wgDeleteRevisionsLimit ) {
2524 $revCount = $this->estimateRevisionCount();
2525 return $revCount > $wgDeleteRevisionsLimit;
2526 }
2527 return false;
2528 }
2529
2530 /**
2531 * @return int approximate revision count
2532 */
2533 public function estimateRevisionCount() {
2534 $dbr = wfGetDB( DB_SLAVE );
2535 // For an exact count...
2536 //return $dbr->selectField( 'revision', 'COUNT(*)',
2537 // array( 'rev_page' => $this->getId() ), __METHOD__ );
2538 return $dbr->estimateRowCount( 'revision', '*',
2539 array( 'rev_page' => $this->getId() ), __METHOD__ );
2540 }
2541
2542 /**
2543 * Get the last N authors
2544 * @param $num Integer: number of revisions to get
2545 * @param $revLatest String: the latest rev_id, selected from the master (optional)
2546 * @return array Array of authors, duplicates not removed
2547 */
2548 public function getLastNAuthors( $num, $revLatest = 0 ) {
2549 wfProfileIn( __METHOD__ );
2550 // First try the slave
2551 // If that doesn't have the latest revision, try the master
2552 $continue = 2;
2553 $db = wfGetDB( DB_SLAVE );
2554 do {
2555 $res = $db->select( array( 'page', 'revision' ),
2556 array( 'rev_id', 'rev_user_text' ),
2557 array(
2558 'page_namespace' => $this->mTitle->getNamespace(),
2559 'page_title' => $this->mTitle->getDBkey(),
2560 'rev_page = page_id'
2561 ), __METHOD__, $this->getSelectOptions( array(
2562 'ORDER BY' => 'rev_timestamp DESC',
2563 'LIMIT' => $num
2564 ) )
2565 );
2566 if( !$res ) {
2567 wfProfileOut( __METHOD__ );
2568 return array();
2569 }
2570 $row = $db->fetchObject( $res );
2571 if( $continue == 2 && $revLatest && $row->rev_id != $revLatest ) {
2572 $db = wfGetDB( DB_MASTER );
2573 $continue--;
2574 } else {
2575 $continue = 0;
2576 }
2577 } while ( $continue );
2578
2579 $authors = array( $row->rev_user_text );
2580 while ( $row = $db->fetchObject( $res ) ) {
2581 $authors[] = $row->rev_user_text;
2582 }
2583 wfProfileOut( __METHOD__ );
2584 return $authors;
2585 }
2586
2587 /**
2588 * Output deletion confirmation dialog
2589 * @param $reason String: prefilled reason
2590 */
2591 public function confirmDelete( $reason ) {
2592 global $wgOut, $wgUser;
2593
2594 wfDebug( "Article::confirmDelete\n" );
2595
2596 $deleteBackLink = $wgUser->getSkin()->link(
2597 $this->mTitle,
2598 null,
2599 array(),
2600 array(),
2601 array( 'known', 'noclasses' )
2602 );
2603 $wgOut->setSubtitle( wfMsgHtml( 'delete-backlink', $deleteBackLink ) );
2604 $wgOut->setRobotPolicy( 'noindex,nofollow' );
2605 $wgOut->addWikiMsg( 'confirmdeletetext' );
2606
2607 if( $wgUser->isAllowed( 'suppressrevision' ) ) {
2608 $suppress = "<tr id=\"wpDeleteSuppressRow\" name=\"wpDeleteSuppressRow\">
2609 <td></td>
2610 <td class='mw-input'><strong>" .
2611 Xml::checkLabel( wfMsg( 'revdelete-suppress' ),
2612 'wpSuppress', 'wpSuppress', false, array( 'tabindex' => '4' ) ) .
2613 "</strong></td>
2614 </tr>";
2615 } else {
2616 $suppress = '';
2617 }
2618 $checkWatch = $wgUser->getBoolOption( 'watchdeletion' ) || $this->mTitle->userIsWatching();
2619
2620 $form = Xml::openElement( 'form', array( 'method' => 'post',
2621 'action' => $this->mTitle->getLocalURL( 'action=delete' ), 'id' => 'deleteconfirm' ) ) .
2622 Xml::openElement( 'fieldset', array( 'id' => 'mw-delete-table' ) ) .
2623 Xml::tags( 'legend', null, wfMsgExt( 'delete-legend', array( 'parsemag', 'escapenoentities' ) ) ) .
2624 Xml::openElement( 'table', array( 'id' => 'mw-deleteconfirm-table' ) ) .
2625 "<tr id=\"wpDeleteReasonListRow\">
2626 <td class='mw-label'>" .
2627 Xml::label( wfMsg( 'deletecomment' ), 'wpDeleteReasonList' ) .
2628 "</td>
2629 <td class='mw-input'>" .
2630 Xml::listDropDown( 'wpDeleteReasonList',
2631 wfMsgForContent( 'deletereason-dropdown' ),
2632 wfMsgForContent( 'deletereasonotherlist' ), '', 'wpReasonDropDown', 1 ) .
2633 "</td>
2634 </tr>
2635 <tr id=\"wpDeleteReasonRow\">
2636 <td class='mw-label'>" .
2637 Xml::label( wfMsg( 'deleteotherreason' ), 'wpReason' ) .
2638 "</td>
2639 <td class='mw-input'>" .
2640 Xml::input( 'wpReason', 60, $reason, array( 'type' => 'text', 'maxlength' => '255',
2641 'tabindex' => '2', 'id' => 'wpReason' ) ) .
2642 "</td>
2643 </tr>
2644 <tr>
2645 <td></td>
2646 <td class='mw-input'>" .
2647 Xml::checkLabel( wfMsg( 'watchthis' ),
2648 'wpWatch', 'wpWatch', $checkWatch, array( 'tabindex' => '3' ) ) .
2649 "</td>
2650 </tr>
2651 $suppress
2652 <tr>
2653 <td></td>
2654 <td class='mw-submit'>" .
2655 Xml::submitButton( wfMsg( 'deletepage' ),
2656 array( 'name' => 'wpConfirmB', 'id' => 'wpConfirmB', 'tabindex' => '5' ) ) .
2657 "</td>
2658 </tr>" .
2659 Xml::closeElement( 'table' ) .
2660 Xml::closeElement( 'fieldset' ) .
2661 Xml::hidden( 'wpEditToken', $wgUser->editToken() ) .
2662 Xml::closeElement( 'form' );
2663
2664 if( $wgUser->isAllowed( 'editinterface' ) ) {
2665 $skin = $wgUser->getSkin();
2666 $title = Title::makeTitle( NS_MEDIAWIKI, 'Deletereason-dropdown' );
2667 $link = $skin->link(
2668 $title,
2669 wfMsgHtml( 'delete-edit-reasonlist' ),
2670 array(),
2671 array( 'action' => 'edit' )
2672 );
2673 $form .= '<p class="mw-delete-editreasons">' . $link . '</p>';
2674 }
2675
2676 $wgOut->addHTML( $form );
2677 $wgOut->addHTML( Xml::element( 'h2', null, LogPage::logName( 'delete' ) ) );
2678 LogEventsList::showLogExtract( $wgOut, 'delete', $this->mTitle->getPrefixedText() );
2679 }
2680
2681 /**
2682 * Perform a deletion and output success or failure messages
2683 */
2684 public function doDelete( $reason, $suppress = false ) {
2685 global $wgOut, $wgUser;
2686 $id = $this->mTitle->getArticleID( GAID_FOR_UPDATE );
2687
2688 $error = '';
2689 if( wfRunHooks('ArticleDelete', array(&$this, &$wgUser, &$reason, &$error)) ) {
2690 if( $this->doDeleteArticle( $reason, $suppress, $id ) ) {
2691 $deleted = $this->mTitle->getPrefixedText();
2692
2693 $wgOut->setPagetitle( wfMsg( 'actioncomplete' ) );
2694 $wgOut->setRobotPolicy( 'noindex,nofollow' );
2695
2696 $loglink = '[[Special:Log/delete|' . wfMsgNoTrans( 'deletionlog' ) . ']]';
2697
2698 $wgOut->addWikiMsg( 'deletedtext', $deleted, $loglink );
2699 $wgOut->returnToMain( false );
2700 wfRunHooks('ArticleDeleteComplete', array(&$this, &$wgUser, $reason, $id));
2701 } else {
2702 if( $error == '' ) {
2703 $wgOut->showFatalError( wfMsgExt( 'cannotdelete', array( 'parse' ) ) );
2704 $wgOut->addHTML( Xml::element( 'h2', null, LogPage::logName( 'delete' ) ) );
2705 LogEventsList::showLogExtract( $wgOut, 'delete', $this->mTitle->getPrefixedText() );
2706 } else {
2707 $wgOut->showFatalError( $error );
2708 }
2709 }
2710 }
2711 }
2712
2713 /**
2714 * Back-end article deletion
2715 * Deletes the article with database consistency, writes logs, purges caches
2716 * Returns success
2717 */
2718 public function doDeleteArticle( $reason, $suppress = false, $id = 0 ) {
2719 global $wgUseSquid, $wgDeferredUpdateList;
2720 global $wgUseTrackbacks;
2721
2722 wfDebug( __METHOD__."\n" );
2723
2724 $dbw = wfGetDB( DB_MASTER );
2725 $ns = $this->mTitle->getNamespace();
2726 $t = $this->mTitle->getDBkey();
2727 $id = $id ? $id : $this->mTitle->getArticleID( GAID_FOR_UPDATE );
2728
2729 if( $t == '' || $id == 0 ) {
2730 return false;
2731 }
2732
2733 $u = new SiteStatsUpdate( 0, 1, -(int)$this->isCountable( $this->getRawText() ), -1 );
2734 array_push( $wgDeferredUpdateList, $u );
2735
2736 // Bitfields to further suppress the content
2737 if( $suppress ) {
2738 $bitfield = 0;
2739 // This should be 15...
2740 $bitfield |= Revision::DELETED_TEXT;
2741 $bitfield |= Revision::DELETED_COMMENT;
2742 $bitfield |= Revision::DELETED_USER;
2743 $bitfield |= Revision::DELETED_RESTRICTED;
2744 } else {
2745 $bitfield = 'rev_deleted';
2746 }
2747
2748 $dbw->begin();
2749 // For now, shunt the revision data into the archive table.
2750 // Text is *not* removed from the text table; bulk storage
2751 // is left intact to avoid breaking block-compression or
2752 // immutable storage schemes.
2753 //
2754 // For backwards compatibility, note that some older archive
2755 // table entries will have ar_text and ar_flags fields still.
2756 //
2757 // In the future, we may keep revisions and mark them with
2758 // the rev_deleted field, which is reserved for this purpose.
2759 $dbw->insertSelect( 'archive', array( 'page', 'revision' ),
2760 array(
2761 'ar_namespace' => 'page_namespace',
2762 'ar_title' => 'page_title',
2763 'ar_comment' => 'rev_comment',
2764 'ar_user' => 'rev_user',
2765 'ar_user_text' => 'rev_user_text',
2766 'ar_timestamp' => 'rev_timestamp',
2767 'ar_minor_edit' => 'rev_minor_edit',
2768 'ar_rev_id' => 'rev_id',
2769 'ar_text_id' => 'rev_text_id',
2770 'ar_text' => '\'\'', // Be explicit to appease
2771 'ar_flags' => '\'\'', // MySQL's "strict mode"...
2772 'ar_len' => 'rev_len',
2773 'ar_page_id' => 'page_id',
2774 'ar_deleted' => $bitfield
2775 ), array(
2776 'page_id' => $id,
2777 'page_id = rev_page'
2778 ), __METHOD__
2779 );
2780
2781 # Delete restrictions for it
2782 $dbw->delete( 'page_restrictions', array ( 'pr_page' => $id ), __METHOD__ );
2783
2784 # Now that it's safely backed up, delete it
2785 $dbw->delete( 'page', array( 'page_id' => $id ), __METHOD__);
2786 $ok = ( $dbw->affectedRows() > 0 ); // getArticleId() uses slave, could be laggy
2787 if( !$ok ) {
2788 $dbw->rollback();
2789 return false;
2790 }
2791
2792 # Fix category table counts
2793 $cats = array();
2794 $res = $dbw->select( 'categorylinks', 'cl_to', array( 'cl_from' => $id ), __METHOD__ );
2795 foreach( $res as $row ) {
2796 $cats []= $row->cl_to;
2797 }
2798 $this->updateCategoryCounts( array(), $cats );
2799
2800 # If using cascading deletes, we can skip some explicit deletes
2801 if( !$dbw->cascadingDeletes() ) {
2802 $dbw->delete( 'revision', array( 'rev_page' => $id ), __METHOD__ );
2803
2804 if($wgUseTrackbacks)
2805 $dbw->delete( 'trackbacks', array( 'tb_page' => $id ), __METHOD__ );
2806
2807 # Delete outgoing links
2808 $dbw->delete( 'pagelinks', array( 'pl_from' => $id ) );
2809 $dbw->delete( 'imagelinks', array( 'il_from' => $id ) );
2810 $dbw->delete( 'categorylinks', array( 'cl_from' => $id ) );
2811 $dbw->delete( 'templatelinks', array( 'tl_from' => $id ) );
2812 $dbw->delete( 'externallinks', array( 'el_from' => $id ) );
2813 $dbw->delete( 'langlinks', array( 'll_from' => $id ) );
2814 $dbw->delete( 'redirect', array( 'rd_from' => $id ) );
2815 }
2816
2817 # If using cleanup triggers, we can skip some manual deletes
2818 if( !$dbw->cleanupTriggers() ) {
2819 # Clean up recentchanges entries...
2820 $dbw->delete( 'recentchanges',
2821 array( 'rc_type != '.RC_LOG,
2822 'rc_namespace' => $this->mTitle->getNamespace(),
2823 'rc_title' => $this->mTitle->getDBkey() ),
2824 __METHOD__ );
2825 $dbw->delete( 'recentchanges',
2826 array( 'rc_type != '.RC_LOG, 'rc_cur_id' => $id ),
2827 __METHOD__ );
2828 }
2829
2830 # Clear caches
2831 Article::onArticleDelete( $this->mTitle );
2832
2833 # Clear the cached article id so the interface doesn't act like we exist
2834 $this->mTitle->resetArticleID( 0 );
2835
2836 # Log the deletion, if the page was suppressed, log it at Oversight instead
2837 $logtype = $suppress ? 'suppress' : 'delete';
2838 $log = new LogPage( $logtype );
2839
2840 # Make sure logging got through
2841 $log->addEntry( 'delete', $this->mTitle, $reason, array() );
2842
2843 $dbw->commit();
2844
2845 return true;
2846 }
2847
2848 /**
2849 * Roll back the most recent consecutive set of edits to a page
2850 * from the same user; fails if there are no eligible edits to
2851 * roll back to, e.g. user is the sole contributor. This function
2852 * performs permissions checks on $wgUser, then calls commitRollback()
2853 * to do the dirty work
2854 *
2855 * @param $fromP String: Name of the user whose edits to rollback.
2856 * @param $summary String: Custom summary. Set to default summary if empty.
2857 * @param $token String: Rollback token.
2858 * @param $bot Boolean: If true, mark all reverted edits as bot.
2859 *
2860 * @param $resultDetails Array: contains result-specific array of additional values
2861 * 'alreadyrolled' : 'current' (rev)
2862 * success : 'summary' (str), 'current' (rev), 'target' (rev)
2863 *
2864 * @return array of errors, each error formatted as
2865 * array(messagekey, param1, param2, ...).
2866 * On success, the array is empty. This array can also be passed to
2867 * OutputPage::showPermissionsErrorPage().
2868 */
2869 public function doRollback( $fromP, $summary, $token, $bot, &$resultDetails ) {
2870 global $wgUser;
2871 $resultDetails = null;
2872
2873 # Check permissions
2874 $editErrors = $this->mTitle->getUserPermissionsErrors( 'edit', $wgUser );
2875 $rollbackErrors = $this->mTitle->getUserPermissionsErrors( 'rollback', $wgUser );
2876 $errors = array_merge( $editErrors, wfArrayDiff2( $rollbackErrors, $editErrors ) );
2877
2878 if( !$wgUser->matchEditToken( $token, array( $this->mTitle->getPrefixedText(), $fromP ) ) )
2879 $errors[] = array( 'sessionfailure' );
2880
2881 if( $wgUser->pingLimiter( 'rollback' ) || $wgUser->pingLimiter() ) {
2882 $errors[] = array( 'actionthrottledtext' );
2883 }
2884 # If there were errors, bail out now
2885 if( !empty( $errors ) )
2886 return $errors;
2887
2888 return $this->commitRollback($fromP, $summary, $bot, $resultDetails);
2889 }
2890
2891 /**
2892 * Backend implementation of doRollback(), please refer there for parameter
2893 * and return value documentation
2894 *
2895 * NOTE: This function does NOT check ANY permissions, it just commits the
2896 * rollback to the DB Therefore, you should only call this function direct-
2897 * ly if you want to use custom permissions checks. If you don't, use
2898 * doRollback() instead.
2899 */
2900 public function commitRollback($fromP, $summary, $bot, &$resultDetails) {
2901 global $wgUseRCPatrol, $wgUser, $wgLang;
2902 $dbw = wfGetDB( DB_MASTER );
2903
2904 if( wfReadOnly() ) {
2905 return array( array( 'readonlytext' ) );
2906 }
2907
2908 # Get the last editor
2909 $current = Revision::newFromTitle( $this->mTitle );
2910 if( is_null( $current ) ) {
2911 # Something wrong... no page?
2912 return array(array('notanarticle'));
2913 }
2914
2915 $from = str_replace( '_', ' ', $fromP );
2916 if( $from != $current->getUserText() ) {
2917 $resultDetails = array( 'current' => $current );
2918 return array(array('alreadyrolled',
2919 htmlspecialchars($this->mTitle->getPrefixedText()),
2920 htmlspecialchars($fromP),
2921 htmlspecialchars($current->getUserText())
2922 ));
2923 }
2924
2925 # Get the last edit not by this guy
2926 $user = intval( $current->getUser() );
2927 $user_text = $dbw->addQuotes( $current->getUserText() );
2928 $s = $dbw->selectRow( 'revision',
2929 array( 'rev_id', 'rev_timestamp', 'rev_deleted' ),
2930 array( 'rev_page' => $current->getPage(),
2931 "rev_user != {$user} OR rev_user_text != {$user_text}"
2932 ), __METHOD__,
2933 array( 'USE INDEX' => 'page_timestamp',
2934 'ORDER BY' => 'rev_timestamp DESC' )
2935 );
2936 if( $s === false ) {
2937 # No one else ever edited this page
2938 return array(array('cantrollback'));
2939 } else if( $s->rev_deleted & REVISION::DELETED_TEXT || $s->rev_deleted & REVISION::DELETED_USER ) {
2940 # Only admins can see this text
2941 return array(array('notvisiblerev'));
2942 }
2943
2944 $set = array();
2945 if( $bot && $wgUser->isAllowed('markbotedits') ) {
2946 # Mark all reverted edits as bot
2947 $set['rc_bot'] = 1;
2948 }
2949 if( $wgUseRCPatrol ) {
2950 # Mark all reverted edits as patrolled
2951 $set['rc_patrolled'] = 1;
2952 }
2953
2954 if( $set ) {
2955 $dbw->update( 'recentchanges', $set,
2956 array( /* WHERE */
2957 'rc_cur_id' => $current->getPage(),
2958 'rc_user_text' => $current->getUserText(),
2959 "rc_timestamp > '{$s->rev_timestamp}'",
2960 ), __METHOD__
2961 );
2962 }
2963
2964 # Generate the edit summary if necessary
2965 $target = Revision::newFromId( $s->rev_id );
2966 if( empty( $summary ) ){
2967 $summary = wfMsgForContent( 'revertpage' );
2968 }
2969
2970 # Allow the custom summary to use the same args as the default message
2971 $args = array(
2972 $target->getUserText(), $from, $s->rev_id,
2973 $wgLang->timeanddate(wfTimestamp(TS_MW, $s->rev_timestamp), true),
2974 $current->getId(), $wgLang->timeanddate($current->getTimestamp())
2975 );
2976 $summary = wfMsgReplaceArgs( $summary, $args );
2977
2978 # Save
2979 $flags = EDIT_UPDATE;
2980
2981 if( $wgUser->isAllowed('minoredit') )
2982 $flags |= EDIT_MINOR;
2983
2984 if( $bot && ($wgUser->isAllowed('markbotedits') || $wgUser->isAllowed('bot')) )
2985 $flags |= EDIT_FORCE_BOT;
2986 # Actually store the edit
2987 $status = $this->doEdit( $target->getText(), $summary, $flags, $target->getId() );
2988 if( !empty( $status->value['revision'] ) ) {
2989 $revId = $status->value['revision']->getId();
2990 } else {
2991 $revId = false;
2992 }
2993
2994 wfRunHooks( 'ArticleRollbackComplete', array( $this, $wgUser, $target, $current ) );
2995
2996 $resultDetails = array(
2997 'summary' => $summary,
2998 'current' => $current,
2999 'target' => $target,
3000 'newid' => $revId
3001 );
3002 return array();
3003 }
3004
3005 /**
3006 * User interface for rollback operations
3007 */
3008 public function rollback() {
3009 global $wgUser, $wgOut, $wgRequest, $wgUseRCPatrol;
3010 $details = null;
3011
3012 $result = $this->doRollback(
3013 $wgRequest->getVal( 'from' ),
3014 $wgRequest->getText( 'summary' ),
3015 $wgRequest->getVal( 'token' ),
3016 $wgRequest->getBool( 'bot' ),
3017 $details
3018 );
3019
3020 if( in_array( array( 'actionthrottledtext' ), $result ) ) {
3021 $wgOut->rateLimited();
3022 return;
3023 }
3024 if( isset( $result[0][0] ) && ( $result[0][0] == 'alreadyrolled' || $result[0][0] == 'cantrollback' ) ) {
3025 $wgOut->setPageTitle( wfMsg( 'rollbackfailed' ) );
3026 $errArray = $result[0];
3027 $errMsg = array_shift( $errArray );
3028 $wgOut->addWikiMsgArray( $errMsg, $errArray );
3029 if( isset( $details['current'] ) ){
3030 $current = $details['current'];
3031 if( $current->getComment() != '' ) {
3032 $wgOut->addWikiMsgArray( 'editcomment', array(
3033 $wgUser->getSkin()->formatComment( $current->getComment() ) ), array( 'replaceafter' ) );
3034 }
3035 }
3036 return;
3037 }
3038 # Display permissions errors before read-only message -- there's no
3039 # point in misleading the user into thinking the inability to rollback
3040 # is only temporary.
3041 if( !empty( $result ) && $result !== array( array( 'readonlytext' ) ) ) {
3042 # array_diff is completely broken for arrays of arrays, sigh. Re-
3043 # move any 'readonlytext' error manually.
3044 $out = array();
3045 foreach( $result as $error ) {
3046 if( $error != array( 'readonlytext' ) ) {
3047 $out []= $error;
3048 }
3049 }
3050 $wgOut->showPermissionsErrorPage( $out );
3051 return;
3052 }
3053 if( $result == array( array( 'readonlytext' ) ) ) {
3054 $wgOut->readOnlyPage();
3055 return;
3056 }
3057
3058 $current = $details['current'];
3059 $target = $details['target'];
3060 $newId = $details['newid'];
3061 $wgOut->setPageTitle( wfMsg( 'actioncomplete' ) );
3062 $wgOut->setRobotPolicy( 'noindex,nofollow' );
3063 $old = $wgUser->getSkin()->userLink( $current->getUser(), $current->getUserText() )
3064 . $wgUser->getSkin()->userToolLinks( $current->getUser(), $current->getUserText() );
3065 $new = $wgUser->getSkin()->userLink( $target->getUser(), $target->getUserText() )
3066 . $wgUser->getSkin()->userToolLinks( $target->getUser(), $target->getUserText() );
3067 $wgOut->addHTML( wfMsgExt( 'rollback-success', array( 'parse', 'replaceafter' ), $old, $new ) );
3068 $wgOut->returnToMain( false, $this->mTitle );
3069
3070 if( !$wgRequest->getBool( 'hidediff', false ) && !$wgUser->getBoolOption( 'norollbackdiff', false ) ) {
3071 $de = new DifferenceEngine( $this->mTitle, $current->getId(), $newId, false, true );
3072 $de->showDiff( '', '' );
3073 }
3074 }
3075
3076
3077 /**
3078 * Do standard deferred updates after page view
3079 */
3080 public function viewUpdates() {
3081 global $wgDeferredUpdateList, $wgDisableCounters, $wgUser;
3082 # Don't update page view counters on views from bot users (bug 14044)
3083 if( !$wgDisableCounters && !$wgUser->isAllowed('bot') && $this->getID() ) {
3084 Article::incViewCount( $this->getID() );
3085 $u = new SiteStatsUpdate( 1, 0, 0 );
3086 array_push( $wgDeferredUpdateList, $u );
3087 }
3088 # Update newtalk / watchlist notification status
3089 $wgUser->clearNotification( $this->mTitle );
3090 }
3091
3092 /**
3093 * Prepare text which is about to be saved.
3094 * Returns a stdclass with source, pst and output members
3095 */
3096 public function prepareTextForEdit( $text, $revid=null ) {
3097 if( $this->mPreparedEdit && $this->mPreparedEdit->newText == $text && $this->mPreparedEdit->revid == $revid) {
3098 // Already prepared
3099 return $this->mPreparedEdit;
3100 }
3101 global $wgParser;
3102 $edit = (object)array();
3103 $edit->revid = $revid;
3104 $edit->newText = $text;
3105 $edit->pst = $this->preSaveTransform( $text );
3106 $options = $this->getParserOptions();
3107 $edit->output = $wgParser->parse( $edit->pst, $this->mTitle, $options, true, true, $revid );
3108 $edit->oldText = $this->getContent();
3109 $this->mPreparedEdit = $edit;
3110 return $edit;
3111 }
3112
3113 /**
3114 * Do standard deferred updates after page edit.
3115 * Update links tables, site stats, search index and message cache.
3116 * Purges pages that include this page if the text was changed here.
3117 * Every 100th edit, prune the recent changes table.
3118 *
3119 * @private
3120 * @param $text New text of the article
3121 * @param $summary Edit summary
3122 * @param $minoredit Minor edit
3123 * @param $timestamp_of_pagechange Timestamp associated with the page change
3124 * @param $newid rev_id value of the new revision
3125 * @param $changed Whether or not the content actually changed
3126 */
3127 public function editUpdates( $text, $summary, $minoredit, $timestamp_of_pagechange, $newid, $changed = true ) {
3128 global $wgDeferredUpdateList, $wgMessageCache, $wgUser, $wgParser, $wgEnableParserCache;
3129
3130 wfProfileIn( __METHOD__ );
3131
3132 # Parse the text
3133 # Be careful not to double-PST: $text is usually already PST-ed once
3134 if( !$this->mPreparedEdit || $this->mPreparedEdit->output->getFlag( 'vary-revision' ) ) {
3135 wfDebug( __METHOD__ . ": No prepared edit or vary-revision is set...\n" );
3136 $editInfo = $this->prepareTextForEdit( $text, $newid );
3137 } else {
3138 wfDebug( __METHOD__ . ": No vary-revision, using prepared edit...\n" );
3139 $editInfo = $this->mPreparedEdit;
3140 }
3141
3142 # Save it to the parser cache
3143 if( $wgEnableParserCache ) {
3144 $popts = $this->getParserOptions();
3145 $parserCache = ParserCache::singleton();
3146 $parserCache->save( $editInfo->output, $this, $popts );
3147 }
3148
3149 # Update the links tables
3150 $u = new LinksUpdate( $this->mTitle, $editInfo->output );
3151 $u->doUpdate();
3152
3153 wfRunHooks( 'ArticleEditUpdates', array( &$this, &$editInfo, $changed ) );
3154
3155 if( wfRunHooks( 'ArticleEditUpdatesDeleteFromRecentchanges', array( &$this ) ) ) {
3156 if( 0 == mt_rand( 0, 99 ) ) {
3157 // Flush old entries from the `recentchanges` table; we do this on
3158 // random requests so as to avoid an increase in writes for no good reason
3159 global $wgRCMaxAge;
3160 $dbw = wfGetDB( DB_MASTER );
3161 $cutoff = $dbw->timestamp( time() - $wgRCMaxAge );
3162 $recentchanges = $dbw->tableName( 'recentchanges' );
3163 $sql = "DELETE FROM $recentchanges WHERE rc_timestamp < '{$cutoff}'";
3164 $dbw->query( $sql );
3165 }
3166 }
3167
3168 $id = $this->getID();
3169 $title = $this->mTitle->getPrefixedDBkey();
3170 $shortTitle = $this->mTitle->getDBkey();
3171
3172 if( 0 == $id ) {
3173 wfProfileOut( __METHOD__ );
3174 return;
3175 }
3176
3177 $u = new SiteStatsUpdate( 0, 1, $this->mGoodAdjustment, $this->mTotalAdjustment );
3178 array_push( $wgDeferredUpdateList, $u );
3179 $u = new SearchUpdate( $id, $title, $text );
3180 array_push( $wgDeferredUpdateList, $u );
3181
3182 # If this is another user's talk page, update newtalk
3183 # Don't do this if $changed = false otherwise some idiot can null-edit a
3184 # load of user talk pages and piss people off, nor if it's a minor edit
3185 # by a properly-flagged bot.
3186 if( $this->mTitle->getNamespace() == NS_USER_TALK && $shortTitle != $wgUser->getTitleKey() && $changed
3187 && !( $minoredit && $wgUser->isAllowed( 'nominornewtalk' ) ) ) {
3188 if( wfRunHooks('ArticleEditUpdateNewTalk', array( &$this ) ) ) {
3189 $other = User::newFromName( $shortTitle, false );
3190 if( !$other ) {
3191 wfDebug( __METHOD__.": invalid username\n" );
3192 } elseif( User::isIP( $shortTitle ) ) {
3193 // An anonymous user
3194 $other->setNewtalk( true );
3195 } elseif( $other->isLoggedIn() ) {
3196 $other->setNewtalk( true );
3197 } else {
3198 wfDebug( __METHOD__. ": don't need to notify a nonexistent user\n" );
3199 }
3200 }
3201 }
3202
3203 if( $this->mTitle->getNamespace() == NS_MEDIAWIKI ) {
3204 $wgMessageCache->replace( $shortTitle, $text );
3205 }
3206
3207 wfProfileOut( __METHOD__ );
3208 }
3209
3210 /**
3211 * Perform article updates on a special page creation.
3212 *
3213 * @param $rev Revision object
3214 *
3215 * @todo This is a shitty interface function. Kill it and replace the
3216 * other shitty functions like editUpdates and such so it's not needed
3217 * anymore.
3218 */
3219 public function createUpdates( $rev ) {
3220 $this->mGoodAdjustment = $this->isCountable( $rev->getText() );
3221 $this->mTotalAdjustment = 1;
3222 $this->editUpdates( $rev->getText(), $rev->getComment(),
3223 $rev->isMinor(), wfTimestamp(), $rev->getId(), true );
3224 }
3225
3226 /**
3227 * Generate the navigation links when browsing through an article revisions
3228 * It shows the information as:
3229 * Revision as of \<date\>; view current revision
3230 * \<- Previous version | Next Version -\>
3231 *
3232 * @param $oldid String: revision ID of this article revision
3233 */
3234 public function setOldSubtitle( $oldid = 0 ) {
3235 global $wgLang, $wgOut, $wgUser, $wgRequest;
3236
3237 if( !wfRunHooks( 'DisplayOldSubtitle', array( &$this, &$oldid ) ) ) {
3238 return;
3239 }
3240
3241 $revision = Revision::newFromId( $oldid );
3242
3243 $current = ( $oldid == $this->mLatest );
3244 $td = $wgLang->timeanddate( $this->mTimestamp, true );
3245 $tddate = $wgLang->date( $this->mTimestamp, true );
3246 $tdtime = $wgLang->time( $this->mTimestamp, true );
3247 $sk = $wgUser->getSkin();
3248 $lnk = $current
3249 ? wfMsgHtml( 'currentrevisionlink' )
3250 : $sk->link(
3251 $this->mTitle,
3252 wfMsgHtml( 'currentrevisionlink' ),
3253 array(),
3254 array(),
3255 array( 'known', 'noclasses' )
3256 );
3257 $curdiff = $current
3258 ? wfMsgHtml( 'diff' )
3259 : $sk->link(
3260 $this->mTitle,
3261 wfMsgHtml( 'diff' ),
3262 array(),
3263 array(
3264 'diff' => 'cur',
3265 'oldid' => $oldid
3266 ),
3267 array( 'known', 'noclasses' )
3268 );
3269 $prev = $this->mTitle->getPreviousRevisionID( $oldid ) ;
3270 $prevlink = $prev
3271 ? $sk->link(
3272 $this->mTitle,
3273 wfMsgHtml( 'previousrevision' ),
3274 array(),
3275 array(
3276 'direction' => 'prev',
3277 'oldid' => $oldid
3278 ),
3279 array( 'known', 'noclasses' )
3280 )
3281 : wfMsgHtml( 'previousrevision' );
3282 $prevdiff = $prev
3283 ? $sk->link(
3284 $this->mTitle,
3285 wfMsgHtml( 'diff' ),
3286 array(),
3287 array(
3288 'diff' => 'prev',
3289 'oldid' => $oldid
3290 ),
3291 array( 'known', 'noclasses' )
3292 )
3293 : wfMsgHtml( 'diff' );
3294 $nextlink = $current
3295 ? wfMsgHtml( 'nextrevision' )
3296 : $sk->link(
3297 $this->mTitle,
3298 wfMsgHtml( 'nextrevision' ),
3299 array(),
3300 array(
3301 'direction' => 'next',
3302 'oldid' => $oldid
3303 ),
3304 array( 'known', 'noclasses' )
3305 );
3306 $nextdiff = $current
3307 ? wfMsgHtml( 'diff' )
3308 : $sk->link(
3309 $this->mTitle,
3310 wfMsgHtml( 'diff' ),
3311 array(),
3312 array(
3313 'diff' => 'next',
3314 'oldid' => $oldid
3315 ),
3316 array( 'known', 'noclasses' )
3317 );
3318
3319 $cdel='';
3320 if( $wgUser->isAllowed( 'deleterevision' ) ) {
3321 $revdel = SpecialPage::getTitleFor( 'Revisiondelete' );
3322 if( $revision->isCurrent() ) {
3323 // We don't handle top deleted edits too well
3324 $cdel = wfMsgHtml( 'rev-delundel' );
3325 } else if( !$revision->userCan( Revision::DELETED_RESTRICTED ) ) {
3326 // If revision was hidden from sysops
3327 $cdel = wfMsgHtml( 'rev-delundel' );
3328 } else {
3329 $cdel = $sk->link(
3330 $revdel,
3331 wfMsgHtml('rev-delundel'),
3332 array(),
3333 array(
3334 'type' => 'revision',
3335 'target' => urlencode( $this->mTitle->getPrefixedDbkey() ),
3336 'ids' => urlencode( $oldid )
3337 ),
3338 array( 'known', 'noclasses' )
3339 );
3340 // Bolden oversighted content
3341 if( $revision->isDeleted( Revision::DELETED_RESTRICTED ) )
3342 $cdel = "<strong>$cdel</strong>";
3343 }
3344 $cdel = "(<small>$cdel</small>) ";
3345 }
3346 $unhide = $wgRequest->getInt('unhide') == 1 && $wgUser->matchEditToken( $wgRequest->getVal('token'), $oldid );
3347 # Show user links if allowed to see them. If hidden, then show them only if requested...
3348 $userlinks = $sk->revUserTools( $revision, !$unhide );
3349
3350 $m = wfMsg( 'revision-info-current' );
3351 $infomsg = $current && !wfEmptyMsg( 'revision-info-current', $m ) && $m != '-'
3352 ? 'revision-info-current'
3353 : 'revision-info';
3354
3355 $r = "\n\t\t\t\t<div id=\"mw-{$infomsg}\">" .
3356 wfMsgExt(
3357 $infomsg,
3358 array( 'parseinline', 'replaceafter' ),
3359 $td,
3360 $userlinks,
3361 $revision->getID(),
3362 $tddate,
3363 $tdtime,
3364 $revision->getUser()
3365 ) .
3366 "</div>\n" .
3367 "\n\t\t\t\t<div id=\"mw-revision-nav\">" . $cdel . wfMsgExt( 'revision-nav', array( 'escapenoentities', 'parsemag', 'replaceafter' ),
3368 $prevdiff, $prevlink, $lnk, $curdiff, $nextlink, $nextdiff ) . "</div>\n\t\t\t";
3369 $wgOut->setSubtitle( $r );
3370 }
3371
3372 /**
3373 * This function is called right before saving the wikitext,
3374 * so we can do things like signatures and links-in-context.
3375 *
3376 * @param $text String
3377 */
3378 public function preSaveTransform( $text ) {
3379 global $wgParser, $wgUser;
3380 return $wgParser->preSaveTransform( $text, $this->mTitle, $wgUser, ParserOptions::newFromUser( $wgUser ) );
3381 }
3382
3383 /* Caching functions */
3384
3385 /**
3386 * checkLastModified returns true if it has taken care of all
3387 * output to the client that is necessary for this request.
3388 * (that is, it has sent a cached version of the page)
3389 */
3390 protected function tryFileCache() {
3391 static $called = false;
3392 if( $called ) {
3393 wfDebug( "Article::tryFileCache(): called twice!?\n" );
3394 return false;
3395 }
3396 $called = true;
3397 if( $this->isFileCacheable() ) {
3398 $cache = new HTMLFileCache( $this->mTitle );
3399 if( $cache->isFileCacheGood( $this->mTouched ) ) {
3400 wfDebug( "Article::tryFileCache(): about to load file\n" );
3401 $cache->loadFromFileCache();
3402 return true;
3403 } else {
3404 wfDebug( "Article::tryFileCache(): starting buffer\n" );
3405 ob_start( array(&$cache, 'saveToFileCache' ) );
3406 }
3407 } else {
3408 wfDebug( "Article::tryFileCache(): not cacheable\n" );
3409 }
3410 return false;
3411 }
3412
3413 /**
3414 * Check if the page can be cached
3415 * @return bool
3416 */
3417 public function isFileCacheable() {
3418 $cacheable = false;
3419 if( HTMLFileCache::useFileCache() ) {
3420 $cacheable = $this->getID() && !$this->mRedirectedFrom;
3421 // Extension may have reason to disable file caching on some pages.
3422 if( $cacheable ) {
3423 $cacheable = wfRunHooks( 'IsFileCacheable', array( &$this ) );
3424 }
3425 }
3426 return $cacheable;
3427 }
3428
3429 /**
3430 * Loads page_touched and returns a value indicating if it should be used
3431 *
3432 */
3433 public function checkTouched() {
3434 if( !$this->mDataLoaded ) {
3435 $this->loadPageData();
3436 }
3437 return !$this->mIsRedirect;
3438 }
3439
3440 /**
3441 * Get the page_touched field
3442 */
3443 public function getTouched() {
3444 # Ensure that page data has been loaded
3445 if( !$this->mDataLoaded ) {
3446 $this->loadPageData();
3447 }
3448 return $this->mTouched;
3449 }
3450
3451 /**
3452 * Get the page_latest field
3453 */
3454 public function getLatest() {
3455 if( !$this->mDataLoaded ) {
3456 $this->loadPageData();
3457 }
3458 return (int)$this->mLatest;
3459 }
3460
3461 /**
3462 * Edit an article without doing all that other stuff
3463 * The article must already exist; link tables etc
3464 * are not updated, caches are not flushed.
3465 *
3466 * @param $text String: text submitted
3467 * @param $comment String: comment submitted
3468 * @param $minor Boolean: whereas it's a minor modification
3469 */
3470 public function quickEdit( $text, $comment = '', $minor = 0 ) {
3471 wfProfileIn( __METHOD__ );
3472
3473 $dbw = wfGetDB( DB_MASTER );
3474 $revision = new Revision( array(
3475 'page' => $this->getId(),
3476 'text' => $text,
3477 'comment' => $comment,
3478 'minor_edit' => $minor ? 1 : 0,
3479 ) );
3480 $revision->insertOn( $dbw );
3481 $this->updateRevisionOn( $dbw, $revision );
3482
3483 wfRunHooks( 'NewRevisionFromEditComplete', array($this, $revision, false, $wgUser) );
3484
3485 wfProfileOut( __METHOD__ );
3486 }
3487
3488 /**
3489 * Used to increment the view counter
3490 *
3491 * @param $id Integer: article id
3492 */
3493 public static function incViewCount( $id ) {
3494 $id = intval( $id );
3495 global $wgHitcounterUpdateFreq, $wgDBtype;
3496
3497 $dbw = wfGetDB( DB_MASTER );
3498 $pageTable = $dbw->tableName( 'page' );
3499 $hitcounterTable = $dbw->tableName( 'hitcounter' );
3500 $acchitsTable = $dbw->tableName( 'acchits' );
3501
3502 if( $wgHitcounterUpdateFreq <= 1 ) {
3503 $dbw->query( "UPDATE $pageTable SET page_counter = page_counter + 1 WHERE page_id = $id" );
3504 return;
3505 }
3506
3507 # Not important enough to warrant an error page in case of failure
3508 $oldignore = $dbw->ignoreErrors( true );
3509
3510 $dbw->query( "INSERT INTO $hitcounterTable (hc_id) VALUES ({$id})" );
3511
3512 $checkfreq = intval( $wgHitcounterUpdateFreq/25 + 1 );
3513 if( (rand() % $checkfreq != 0) or ($dbw->lastErrno() != 0) ){
3514 # Most of the time (or on SQL errors), skip row count check
3515 $dbw->ignoreErrors( $oldignore );
3516 return;
3517 }
3518
3519 $res = $dbw->query("SELECT COUNT(*) as n FROM $hitcounterTable");
3520 $row = $dbw->fetchObject( $res );
3521 $rown = intval( $row->n );
3522 if( $rown >= $wgHitcounterUpdateFreq ){
3523 wfProfileIn( 'Article::incViewCount-collect' );
3524 $old_user_abort = ignore_user_abort( true );
3525
3526 if($wgDBtype == 'mysql')
3527 $dbw->query("LOCK TABLES $hitcounterTable WRITE");
3528 $tabletype = $wgDBtype == 'mysql' ? "ENGINE=HEAP " : '';
3529 $dbw->query("CREATE TEMPORARY TABLE $acchitsTable $tabletype AS ".
3530 "SELECT hc_id,COUNT(*) AS hc_n FROM $hitcounterTable ".
3531 'GROUP BY hc_id');
3532 $dbw->query("DELETE FROM $hitcounterTable");
3533 if($wgDBtype == 'mysql') {
3534 $dbw->query('UNLOCK TABLES');
3535 $dbw->query("UPDATE $pageTable,$acchitsTable SET page_counter=page_counter + hc_n ".
3536 'WHERE page_id = hc_id');
3537 }
3538 else {
3539 $dbw->query("UPDATE $pageTable SET page_counter=page_counter + hc_n ".
3540 "FROM $acchitsTable WHERE page_id = hc_id");
3541 }
3542 $dbw->query("DROP TABLE $acchitsTable");
3543
3544 ignore_user_abort( $old_user_abort );
3545 wfProfileOut( 'Article::incViewCount-collect' );
3546 }
3547 $dbw->ignoreErrors( $oldignore );
3548 }
3549
3550 /**#@+
3551 * The onArticle*() functions are supposed to be a kind of hooks
3552 * which should be called whenever any of the specified actions
3553 * are done.
3554 *
3555 * This is a good place to put code to clear caches, for instance.
3556 *
3557 * This is called on page move and undelete, as well as edit
3558 *
3559 * @param $title a title object
3560 */
3561
3562 public static function onArticleCreate( $title ) {
3563 # Update existence markers on article/talk tabs...
3564 if( $title->isTalkPage() ) {
3565 $other = $title->getSubjectPage();
3566 } else {
3567 $other = $title->getTalkPage();
3568 }
3569 $other->invalidateCache();
3570 $other->purgeSquid();
3571
3572 $title->touchLinks();
3573 $title->purgeSquid();
3574 $title->deleteTitleProtection();
3575 }
3576
3577 public static function onArticleDelete( $title ) {
3578 global $wgMessageCache;
3579 # Update existence markers on article/talk tabs...
3580 if( $title->isTalkPage() ) {
3581 $other = $title->getSubjectPage();
3582 } else {
3583 $other = $title->getTalkPage();
3584 }
3585 $other->invalidateCache();
3586 $other->purgeSquid();
3587
3588 $title->touchLinks();
3589 $title->purgeSquid();
3590
3591 # File cache
3592 HTMLFileCache::clearFileCache( $title );
3593
3594 # Messages
3595 if( $title->getNamespace() == NS_MEDIAWIKI ) {
3596 $wgMessageCache->replace( $title->getDBkey(), false );
3597 }
3598 # Images
3599 if( $title->getNamespace() == NS_FILE ) {
3600 $update = new HTMLCacheUpdate( $title, 'imagelinks' );
3601 $update->doUpdate();
3602 }
3603 # User talk pages
3604 if( $title->getNamespace() == NS_USER_TALK ) {
3605 $user = User::newFromName( $title->getText(), false );
3606 $user->setNewtalk( false );
3607 }
3608 # Image redirects
3609 RepoGroup::singleton()->getLocalRepo()->invalidateImageRedirect( $title );
3610 }
3611
3612 /**
3613 * Purge caches on page update etc
3614 */
3615 public static function onArticleEdit( $title, $flags = '' ) {
3616 global $wgDeferredUpdateList;
3617
3618 // Invalidate caches of articles which include this page
3619 $wgDeferredUpdateList[] = new HTMLCacheUpdate( $title, 'templatelinks' );
3620
3621 // Invalidate the caches of all pages which redirect here
3622 $wgDeferredUpdateList[] = new HTMLCacheUpdate( $title, 'redirect' );
3623
3624 # Purge squid for this page only
3625 $title->purgeSquid();
3626
3627 # Clear file cache for this page only
3628 HTMLFileCache::clearFileCache( $title );
3629 }
3630
3631 /**#@-*/
3632
3633 /**
3634 * Overriden by ImagePage class, only present here to avoid a fatal error
3635 * Called for ?action=revert
3636 */
3637 public function revert() {
3638 global $wgOut;
3639 $wgOut->showErrorPage( 'nosuchaction', 'nosuchactiontext' );
3640 }
3641
3642 /**
3643 * Info about this page
3644 * Called for ?action=info when $wgAllowPageInfo is on.
3645 */
3646 public function info() {
3647 global $wgLang, $wgOut, $wgAllowPageInfo, $wgUser;
3648
3649 if( !$wgAllowPageInfo ) {
3650 $wgOut->showErrorPage( 'nosuchaction', 'nosuchactiontext' );
3651 return;
3652 }
3653
3654 $page = $this->mTitle->getSubjectPage();
3655
3656 $wgOut->setPagetitle( $page->getPrefixedText() );
3657 $wgOut->setPageTitleActionText( wfMsg( 'info_short' ) );
3658 $wgOut->setSubtitle( wfMsgHtml( 'infosubtitle' ) );
3659
3660 if( !$this->mTitle->exists() ) {
3661 $wgOut->addHTML( '<div class="noarticletext">' );
3662 if( $this->mTitle->getNamespace() == NS_MEDIAWIKI ) {
3663 // This doesn't quite make sense; the user is asking for
3664 // information about the _page_, not the message... -- RC
3665 $wgOut->addHTML( htmlspecialchars( wfMsgWeirdKey( $this->mTitle->getText() ) ) );
3666 } else {
3667 $msg = $wgUser->isLoggedIn()
3668 ? 'noarticletext'
3669 : 'noarticletextanon';
3670 $wgOut->addHTML( wfMsgExt( $msg, 'parse' ) );
3671 }
3672 $wgOut->addHTML( '</div>' );
3673 } else {
3674 $dbr = wfGetDB( DB_SLAVE );
3675 $wl_clause = array(
3676 'wl_title' => $page->getDBkey(),
3677 'wl_namespace' => $page->getNamespace() );
3678 $numwatchers = $dbr->selectField(
3679 'watchlist',
3680 'COUNT(*)',
3681 $wl_clause,
3682 __METHOD__,
3683 $this->getSelectOptions() );
3684
3685 $pageInfo = $this->pageCountInfo( $page );
3686 $talkInfo = $this->pageCountInfo( $page->getTalkPage() );
3687
3688 $wgOut->addHTML( "<ul><li>" . wfMsg("numwatchers", $wgLang->formatNum( $numwatchers ) ) . '</li>' );
3689 $wgOut->addHTML( "<li>" . wfMsg('numedits', $wgLang->formatNum( $pageInfo['edits'] ) ) . '</li>');
3690 if( $talkInfo ) {
3691 $wgOut->addHTML( '<li>' . wfMsg("numtalkedits", $wgLang->formatNum( $talkInfo['edits'] ) ) . '</li>');
3692 }
3693 $wgOut->addHTML( '<li>' . wfMsg("numauthors", $wgLang->formatNum( $pageInfo['authors'] ) ) . '</li>' );
3694 if( $talkInfo ) {
3695 $wgOut->addHTML( '<li>' . wfMsg('numtalkauthors', $wgLang->formatNum( $talkInfo['authors'] ) ) . '</li>' );
3696 }
3697 $wgOut->addHTML( '</ul>' );
3698 }
3699 }
3700
3701 /**
3702 * Return the total number of edits and number of unique editors
3703 * on a given page. If page does not exist, returns false.
3704 *
3705 * @param $title Title object
3706 * @return array
3707 */
3708 public function pageCountInfo( $title ) {
3709 $id = $title->getArticleId();
3710 if( $id == 0 ) {
3711 return false;
3712 }
3713 $dbr = wfGetDB( DB_SLAVE );
3714 $rev_clause = array( 'rev_page' => $id );
3715 $edits = $dbr->selectField(
3716 'revision',
3717 'COUNT(rev_page)',
3718 $rev_clause,
3719 __METHOD__,
3720 $this->getSelectOptions()
3721 );
3722 $authors = $dbr->selectField(
3723 'revision',
3724 'COUNT(DISTINCT rev_user_text)',
3725 $rev_clause,
3726 __METHOD__,
3727 $this->getSelectOptions()
3728 );
3729 return array( 'edits' => $edits, 'authors' => $authors );
3730 }
3731
3732 /**
3733 * Return a list of templates used by this article.
3734 * Uses the templatelinks table
3735 *
3736 * @return Array of Title objects
3737 */
3738 public function getUsedTemplates() {
3739 $result = array();
3740 $id = $this->mTitle->getArticleID();
3741 if( $id == 0 ) {
3742 return array();
3743 }
3744 $dbr = wfGetDB( DB_SLAVE );
3745 $res = $dbr->select( array( 'templatelinks' ),
3746 array( 'tl_namespace', 'tl_title' ),
3747 array( 'tl_from' => $id ),
3748 __METHOD__ );
3749 if( $res !== false ) {
3750 foreach( $res as $row ) {
3751 $result[] = Title::makeTitle( $row->tl_namespace, $row->tl_title );
3752 }
3753 }
3754 $dbr->freeResult( $res );
3755 return $result;
3756 }
3757
3758 /**
3759 * Returns a list of hidden categories this page is a member of.
3760 * Uses the page_props and categorylinks tables.
3761 *
3762 * @return Array of Title objects
3763 */
3764 public function getHiddenCategories() {
3765 $result = array();
3766 $id = $this->mTitle->getArticleID();
3767 if( $id == 0 ) {
3768 return array();
3769 }
3770 $dbr = wfGetDB( DB_SLAVE );
3771 $res = $dbr->select( array( 'categorylinks', 'page_props', 'page' ),
3772 array( 'cl_to' ),
3773 array( 'cl_from' => $id, 'pp_page=page_id', 'pp_propname' => 'hiddencat',
3774 'page_namespace' => NS_CATEGORY, 'page_title=cl_to'),
3775 __METHOD__ );
3776 if( $res !== false ) {
3777 foreach( $res as $row ) {
3778 $result[] = Title::makeTitle( NS_CATEGORY, $row->cl_to );
3779 }
3780 }
3781 $dbr->freeResult( $res );
3782 return $result;
3783 }
3784
3785 /**
3786 * Return an applicable autosummary if one exists for the given edit.
3787 * @param $oldtext String: the previous text of the page.
3788 * @param $newtext String: The submitted text of the page.
3789 * @param $flags Bitmask: a bitmask of flags submitted for the edit.
3790 * @return string An appropriate autosummary, or an empty string.
3791 */
3792 public static function getAutosummary( $oldtext, $newtext, $flags ) {
3793 # Decide what kind of autosummary is needed.
3794
3795 # Redirect autosummaries
3796 $ot = Title::newFromRedirect( $oldtext );
3797 $rt = Title::newFromRedirect( $newtext );
3798 if( is_object( $rt ) && ( !is_object( $ot ) || !$rt->equals( $ot ) || $ot->getFragment() != $rt->getFragment() ) ) {
3799 return wfMsgForContent( 'autoredircomment', $rt->getFullText() );
3800 }
3801
3802 # New page autosummaries
3803 if( $flags & EDIT_NEW && strlen( $newtext ) ) {
3804 # If they're making a new article, give its text, truncated, in the summary.
3805 global $wgContLang;
3806 $truncatedtext = $wgContLang->truncate(
3807 str_replace("\n", ' ', $newtext),
3808 max( 0, 200 - strlen( wfMsgForContent( 'autosumm-new' ) ) ) );
3809 return wfMsgForContent( 'autosumm-new', $truncatedtext );
3810 }
3811
3812 # Blanking autosummaries
3813 if( $oldtext != '' && $newtext == '' ) {
3814 return wfMsgForContent( 'autosumm-blank' );
3815 } elseif( strlen( $oldtext ) > 10 * strlen( $newtext ) && strlen( $newtext ) < 500) {
3816 # Removing more than 90% of the article
3817 global $wgContLang;
3818 $truncatedtext = $wgContLang->truncate(
3819 $newtext,
3820 max( 0, 200 - strlen( wfMsgForContent( 'autosumm-replace' ) ) ) );
3821 return wfMsgForContent( 'autosumm-replace', $truncatedtext );
3822 }
3823
3824 # If we reach this point, there's no applicable autosummary for our case, so our
3825 # autosummary is empty.
3826 return '';
3827 }
3828
3829 /**
3830 * Add the primary page-view wikitext to the output buffer
3831 * Saves the text into the parser cache if possible.
3832 * Updates templatelinks if it is out of date.
3833 *
3834 * @param $text String
3835 * @param $cache Boolean
3836 */
3837 public function outputWikiText( $text, $cache = true, $parserOptions = false ) {
3838 global $wgOut;
3839
3840 $parserOutput = $this->getOutputFromWikitext( $text, $cache, $parserOptions );
3841 $wgOut->addParserOutput( $parserOutput );
3842 }
3843
3844 /**
3845 * This does all the heavy lifting for outputWikitext, except it returns the parser
3846 * output instead of sending it straight to $wgOut. Makes things nice and simple for,
3847 * say, embedding thread pages within a discussion system (LiquidThreads)
3848 */
3849 public function getOutputFromWikitext( $text, $cache = true, $parserOptions = false ) {
3850 global $wgParser, $wgOut, $wgEnableParserCache, $wgUseFileCache;
3851
3852 if ( !$parserOptions ) {
3853 $parserOptions = $this->getParserOptions();
3854 }
3855
3856 $time = -wfTime();
3857 $parserOutput = $wgParser->parse( $text, $this->mTitle,
3858 $parserOptions, true, true, $this->getRevIdFetched() );
3859 $time += wfTime();
3860
3861 # Timing hack
3862 if( $time > 3 ) {
3863 wfDebugLog( 'slow-parse', sprintf( "%-5.2f %s", $time,
3864 $this->mTitle->getPrefixedDBkey()));
3865 }
3866
3867 if( $wgEnableParserCache && $cache && $this && $parserOutput->getCacheTime() != -1 ) {
3868 $parserCache = ParserCache::singleton();
3869 $parserCache->save( $parserOutput, $this, $parserOptions );
3870 }
3871 // Make sure file cache is not used on uncacheable content.
3872 // Output that has magic words in it can still use the parser cache
3873 // (if enabled), though it will generally expire sooner.
3874 if( $parserOutput->getCacheTime() == -1 || $parserOutput->containsOldMagic() ) {
3875 $wgUseFileCache = false;
3876 }
3877 $this->doCascadeProtectionUpdates( $parserOutput );
3878 return $parserOutput;
3879 }
3880
3881 /**
3882 * Get parser options suitable for rendering the primary article wikitext
3883 */
3884 public function getParserOptions() {
3885 global $wgUser;
3886 if ( !$this->mParserOptions ) {
3887 $this->mParserOptions = new ParserOptions( $wgUser );
3888 $this->mParserOptions->setTidy( true );
3889 $this->mParserOptions->enableLimitReport();
3890 }
3891 return $this->mParserOptions;
3892 }
3893
3894 protected function doCascadeProtectionUpdates( $parserOutput ) {
3895 if( !$this->isCurrent() || wfReadOnly() || !$this->mTitle->areRestrictionsCascading() ) {
3896 return;
3897 }
3898
3899 // templatelinks table may have become out of sync,
3900 // especially if using variable-based transclusions.
3901 // For paranoia, check if things have changed and if
3902 // so apply updates to the database. This will ensure
3903 // that cascaded protections apply as soon as the changes
3904 // are visible.
3905
3906 # Get templates from templatelinks
3907 $id = $this->mTitle->getArticleID();
3908
3909 $tlTemplates = array();
3910
3911 $dbr = wfGetDB( DB_SLAVE );
3912 $res = $dbr->select( array( 'templatelinks' ),
3913 array( 'tl_namespace', 'tl_title' ),
3914 array( 'tl_from' => $id ),
3915 __METHOD__ );
3916
3917 global $wgContLang;
3918 foreach( $res as $row ) {
3919 $tlTemplates["{$row->tl_namespace}:{$row->tl_title}"] = true;
3920 }
3921
3922 # Get templates from parser output.
3923 $poTemplates = array();
3924 foreach ( $parserOutput->getTemplates() as $ns => $templates ) {
3925 foreach ( $templates as $dbk => $id ) {
3926 $poTemplates["$ns:$dbk"] = true;
3927 }
3928 }
3929
3930 # Get the diff
3931 # Note that we simulate array_diff_key in PHP <5.0.x
3932 $templates_diff = array_diff_key( $poTemplates, $tlTemplates );
3933
3934 if( count( $templates_diff ) > 0 ) {
3935 # Whee, link updates time.
3936 $u = new LinksUpdate( $this->mTitle, $parserOutput, false );
3937 $u->doUpdate();
3938 }
3939 }
3940
3941 /**
3942 * Update all the appropriate counts in the category table, given that
3943 * we've added the categories $added and deleted the categories $deleted.
3944 *
3945 * @param $added array The names of categories that were added
3946 * @param $deleted array The names of categories that were deleted
3947 * @return null
3948 */
3949 public function updateCategoryCounts( $added, $deleted ) {
3950 $ns = $this->mTitle->getNamespace();
3951 $dbw = wfGetDB( DB_MASTER );
3952
3953 # First make sure the rows exist. If one of the "deleted" ones didn't
3954 # exist, we might legitimately not create it, but it's simpler to just
3955 # create it and then give it a negative value, since the value is bogus
3956 # anyway.
3957 #
3958 # Sometimes I wish we had INSERT ... ON DUPLICATE KEY UPDATE.
3959 $insertCats = array_merge( $added, $deleted );
3960 if( !$insertCats ) {
3961 # Okay, nothing to do
3962 return;
3963 }
3964 $insertRows = array();
3965 foreach( $insertCats as $cat ) {
3966 $insertRows[] = array( 'cat_title' => $cat );
3967 }
3968 $dbw->insert( 'category', $insertRows, __METHOD__, 'IGNORE' );
3969
3970 $addFields = array( 'cat_pages = cat_pages + 1' );
3971 $removeFields = array( 'cat_pages = cat_pages - 1' );
3972 if( $ns == NS_CATEGORY ) {
3973 $addFields[] = 'cat_subcats = cat_subcats + 1';
3974 $removeFields[] = 'cat_subcats = cat_subcats - 1';
3975 } elseif( $ns == NS_FILE ) {
3976 $addFields[] = 'cat_files = cat_files + 1';
3977 $removeFields[] = 'cat_files = cat_files - 1';
3978 }
3979
3980 if( $added ) {
3981 $dbw->update(
3982 'category',
3983 $addFields,
3984 array( 'cat_title' => $added ),
3985 __METHOD__
3986 );
3987 }
3988 if( $deleted ) {
3989 $dbw->update(
3990 'category',
3991 $removeFields,
3992 array( 'cat_title' => $deleted ),
3993 __METHOD__
3994 );
3995 }
3996 }
3997
3998 /** Lightweight method to get the parser output for a page, checking the parser cache
3999 * and so on. Doesn't consider most of the stuff that Article::view is forced to
4000 * consider, so it's not appropriate to use there. */
4001 function getParserOutput( $oldid = null ) {
4002 global $wgEnableParserCache, $wgUser, $wgOut;
4003
4004 // Should the parser cache be used?
4005 $useParserCache = $wgEnableParserCache &&
4006 intval( $wgUser->getOption( 'stubthreshold' ) ) == 0 &&
4007 $this->exists() &&
4008 $oldid === null;
4009
4010 wfDebug( __METHOD__.': using parser cache: ' . ( $useParserCache ? 'yes' : 'no' ) . "\n" );
4011 if ( $wgUser->getOption( 'stubthreshold' ) ) {
4012 wfIncrStats( 'pcache_miss_stub' );
4013 }
4014
4015 $parserOutput = false;
4016 if ( $useParserCache ) {
4017 $parserOutput = ParserCache::singleton()->get( $this, $this->getParserOptions() );
4018 }
4019
4020 if ( $parserOutput === false ) {
4021 // Cache miss; parse and output it.
4022 $rev = Revision::newFromTitle( $this->getTitle(), $oldid );
4023
4024 return $this->getOutputFromWikitext( $rev->getText(), $useParserCache );
4025 } else {
4026 return $parserOutput;
4027 }
4028 }
4029 }